I\'m using the DropDownListFor helper method inside of an edit page and I\'m not having any luck getting it to select the value that I specify. I noticed a similar question
Try:
<%= Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")%>
or in Razor syntax:
@Html.DropDownListFor(
model => model.AddressStateAbbr,
new SelectList(
Model.States.OrderBy(s => s.StateAbbr),
"StateAbbr",
"StateName",
Model.AddressStateAbbr), "-- Select State --")
The expression based helpers don't seem to respect the Selected property of the SelectListItems in your SelectList.
I also having similar issue and I solve it by as follows, set the
model.States property on your controller to what you need to be selected
model.States="California"
and then you will get "California" as default value.
this problem is common. change viewbag property name to other then model variable name used on page.
If you're doing it properly and using a model--unlike all these ViewBag weirdos--and still seeing the issue, it's because @Html.DropDownListFor(m => m.MyValue, @Model.MyOptions)
can't match MyValue
with the choices it has in MyOptions
. The two potential reasons for that are:
MyValue
is null. You haven't set it in your ViewModel. Making one of MyOptions
have a Selected=true
won't solve this.MyValue
is different than the types in MyOptions
. So like, if MyValue
is (int) 1
, but your MyOptions
are a list of padded strings {"01", "02", "03", ...}
, it's obviously not going to select anything.I know this is an old question but I have been having the same issue in 2020.
It turns out the issue was with the model property being called "Title", I renamed it to "GivenTitle" and it now works as expected.
From
Html.DropDownListFor(m => m.Title, Model.Titles, "Please Select", new { @class = "form-control" })
to
Html.DropDownListFor(m => m.GivenTitle, Model.GivenTitles, "Please Select", new { @class = "form-control" })
While not addressing this question - it may help future googlers if they followed my thought path:
I wanted a multiple select and this attribute hack on DropDownListFor wasn't auto selecting
Html.DropDownListFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems, new {multiple= "multiple" })
instead I should have been using ListBoxFor which made everything work
Html.ListBoxFor(m => m.TrainingLevelSelected, Model.TrainingLevelSelectListItems)