The Selected
property in SelectListItem
is mostly useless (more about that in my answer here). The HTML helpers will ignore it in most cases. Instead, in your case, they will look at the values of:
ModelState["IncludesWeekends"]
ViewData["IncludesWeekends"]
Model.IncludesWeekends
... and turn whatever value they find into a String
, then use that as the selected value.
You have an IncludesWeekends
property on your model, so it will do:
Model.IncludesWeekends.ToString()
... which - judging from your code - will result in True" or "False" (since it's a bool
).
In your case, you're using c.Id.ToString()
as the <option>
values for your dropdown, and since the helper won't find its chosen string ("True"/"False") among those values ("1"/"0"), it won't select anything.
Ways around it:
(Easiest way): Accept using "True" and "False" as your
<option>
values rather than integer IDs.(The almost-as-easy-but-not-very-clean way): Set
ViewData["IncludesWeekends"]
to the value you want selected (i.e., theId
). This works, because the helper will look at that beforeModel.IncludesWeekends
.Use a view model, where you have an
IncludesWeekendsId
property, then use that to generate the dropdown, rather thanIncludesWeekends
:<%= Html.DropDownList("IncludesWeekendsId", Model.YesNoList) %>
or
<%= Html.DropDownListFor(m => m.IncludesWeekendsId, Model.YesNoList) %>
Then, when returning from the view, translate
IncludesWeekendsId
back into the proper value on your model.
In this case, I'd probably go with 1 if I wasn't in a pedantic mood. But solution 3 is a general, and mostly clean, way to solve this in cases where you have to use different values for your dropdown items than the value of your model's property converted to a string.