I have this to populate a drop down list in an ASP.NET MVC view.
<%= Html.DropDownListFor(model => model.Bikes,
Model.Bikes.Select(
x => new SelectListItem {
Text = x.Name,
Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
Selected = x.ID == Model.ID,
})) %>
Debugging this I can see that the Selected property is set to true when it should be. But when the view is rendered, none of the options in the list is selected. I realize that this could be done with another overload of DropDownListFor but I really want to get this version working.
Any ideas?
The reason your selected value doesn’t work is because you are using Urls as option values but specifyingModel.IDin theSelectedclause.Try like this:
"Id"indicates the property that will be used as option value while"Name"indicates the property that will be used as option label.If you want to preserve the
Url.Actionyou could try:You will notice that I’ve inverted the Name and Id as it seemed more logical to use the model Id as option value.
UPDATE:
The reason this doesn’t work is because you are binding to an
IEnumerable(the first argument of theDropDownListForhelper). It should be a scalar property while you are using the samemodel.Bikescollection:My remark about not using Urls as option values stands true.