Choose which option is selected in pageload from razor html.dropdownlistfor

I have a drop-down list for the one created with the razor, which displays 2 options: show or hide, and they have the corresponding values ​​of "0" and "1".

 if (Model.Valeur == 0)
 {
      @Html.DropDownListFor(m => m.Valeur,
      new List<SelectListItem> {
      new SelectListItem { Value = "0" , Text = "Show", Selected = true },
      new SelectListItem { Value = "1" , Text = "Hide" },
      }, new { @class = "myselect" })
 }
 else
 {
     @Html.DropDownListFor(m => m.Valeur,
     new List<SelectListItem> {
     new SelectListItem { Value = "0" , Text = "Show" },
     new SelectListItem { Value = "1" , Text = "Hide",  Selected = true },
     }, new { @class = "myselect" })
 }

The if condition I made can set the correct value when the page loads, but I was wondering if there is a way to set the selected value using a parameter or another parameter

Any information would be appreciated.

+4
source share
1 answer

You can use the abbreviated form to determine which option is selected.

 @Html.DropDownListFor(m => m.Valeur,
 new List<SelectListItem> {
 new SelectListItem { Value = "0" , Text = "Show", Selected = Model.Valeur == 0 },
 new SelectListItem { Value = "1" , Text = "Hide", Selected = Model.Valeur != 0 },
 }, new { @class = "myselect" })
+5

Source: https://habr.com/ru/post/1675710/


All Articles