views:

220

answers:

1

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?

+2  A: 
Darin Dimitrov
Note that in my original question the values are URLs.
Deniz Dogan
Yes, I've noticed this, but as this seemed to me a bad idea I've inverted them. By the way that's the reason why your selected value doesn't work. You are passing Model.Id as selected values and using urls as option values. No good. I would recommend you preserving the ID as option value and if necessary fetch the corresponding URL in the controller action you are submitting to. I don't see reasonable to use urls as option values.
Darin Dimitrov
In my original code I'm not passing IDs as selected values and URLs as option values. What I'm doing is setting the values to URLs and then using a condition which should hold for the item to be selected. And is there really any compelling reason as to why I should not be using URLs for values?
Deniz Dogan
Please see my update.
Darin Dimitrov
Looking at the source code of `DropDownList` (or specifically `SelectInternal`) in .NET Reflector it's unclear to me whether the `Selected` property is meant to be set by the user or not. It does seem like it has no effect, so I guess I'll just have to forget about it. Thanks for your patience.
Deniz Dogan