Search code examples
javascriptasp.net-core-mvchtml.dropdownlistfor

GetEnumSelectList overrides the default selected option values


I am loading EnumData to a dropdown list, but default value is getting overridden. When I changed the default values of Enum to start with 1 rather 0(since it is default) by that time default value showing up but if Enum starts from 0(default), default selected value in dropdown overrides with the first enum selection.

Below is my code:

  <div class="form-group row">
    <label asp-for="Feature" class="col-md-4 control-label"></label>
    <div class="col-md-8">
      <select asp-for="Feature" asp-items="Html.GetEnumSelectList<Features.FeatureType>()">
        <option selected="selected" value="">Please select</option>
      </select>
     </div>
  </div>

When I opened developer tools in browser saw 2 dropdown values selected attribute assigned to "selected".

<option selected="**selected**" value="">Please select</option>
<option selected="**selected**" value="0">Feature 0</option>
<option value="1">Feature 1</option>
<option value="2">Feature 2</option>
<option value="3">Feature 3</option>

How to overcome from this problem?


Solution

  • You can try two ways:

    1.Remove the asp-for tag helper in select element. Manully add its name and id.

      <select name="Feature" id="Feature" asp-items="Html.GetEnumSelectList<Features.FeatureType>()">
          <option selected="selected" value="">Please select</option>
      </select>
    

    2.Write js to set the selected option:

    <script>
        $("select").prop("selectedIndex", 0);
    </script>