DropDownList setting selected item in asp.net MVC

I think the problem is a confusion regarding the DropDownList overloads:

  1. Html.DropDownList(string name) looks for a view model property of name and type IEnumerable<SelectListItem>. It will use the selected item (SelectListItem.Selected == true) from the list, unless there is a form post value of the same name.

  2. Html.DropDownList(string name, IEnumerable<SelectListItem> selectList) uses the items from selectList, but not their selected values. The selected is found by resolving name in the view model (or post data) and matching it against the SelectListItem.Value. Even if the value cannot be found (or is null), it still won’t use the selected value from the list of SelectListItems.

Your code uses the second overload, but specifies a “value” property that doesn’t exist (“MultipleServicers”).

To fix your problem, either use the first overload:

<%= Html.DropDownList("IsMultipleServicers") %>

Or, add a string MultipleServicers property to your view model and populate it in your controller. I’d recommend this solution as it gets around several problems with initial display, post display and mapping the post data to a view/post model:

public class ServiceViewModel : ViewModel 
{ 
     public string MultipleServicers { get; set; } 
     public List<SelectListItem> IsMultipleServicers { get; set; } 
}

Then for your HTML:

<%= Html.DropDownList(Model.MultipleServicers, Model.IsMultipleServicers) %>

This technique maps into MVC2, as well:

<%= Html.DropDownListFor(x => x.MultipleServicers, Model.IsMultipleServicers) %>

Leave a Comment