Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: DropDownListFor doesn't select any option

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?

like image 621
Deniz Dogan Avatar asked Jul 28 '10 11:07

Deniz Dogan


1 Answers

The reason your selected value doesn't work is because you are using Urls as option values but specifying Model.ID in the Selected clause.

Try like this:

<%= Html.DropDownListFor(
    model => model.Bikes,
    new SelectList(Model.Bikes, "Id", "Name", Model.ID)
)%>

"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.Action you could try:

<%= Html.DropDownListFor(
    model => model.Bikes,
    new SelectList(Model.Bikes.Select(x => new {
        Id = x.Id,
        Name = Url.Action("Details", "Bike", new { bikeId = x.ID })
    }), "Id", "Name", Model.ID)
)%>

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 the DropDownListFor helper). It should be a scalar property while you are using the same model.Bikes collection:

<%= Html.DropDownListFor(
    model => model.SelectedBikeValue,
    Model.Bikes.Select(
        x => new SelectListItem {
                 Text = x.Name,
                 Value = Url.Action("Details", "Bike", new { bikeId = x.ID }),
                 Selected = x.ID == Model.ID,
        }
)) %>

My remark about not using Urls as option values stands true.

like image 131
Darin Dimitrov Avatar answered Sep 24 '22 13:09

Darin Dimitrov