I noticed that it seems to me an error in asp.net MVC or just that I am doing something wrong. I am currently using 1.0, so maybe this is what will be covered in version 2.0. But anyway, we go.
When my view model has a property whose name matches the declared identifier for the drop-down list, the selected item is ignored and the displayed html did not select anything. Not sure if I did something wrong, but changing the identifier name fixes the problem. I simplified the example, I hope this is understandable, otherwise, please let me know.
Here is my view where the declared identifier matches my list in the model:
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <%= Html.DropDownList("IsMultipleServicers", Model.IsMultipleServicers) %> </td> </tr> </table>
And provided by Html
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <select id="IsMultipleServicers" name="IsMultipleServicers"> <option value="false">No</option> <option value="true">Yes</option> </select> </td> </tr> </table>
Now make a small change. I will change the declared identifier to something else.
Here is my view:
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <%= Html.DropDownList("MultipleServicers", Model.IsMultipleServicers) %> </td> </tr> </table>
And now html rendered:
<table border="0" cellpadding="0" cellspacing="0"> <tr> <td> <select id="IsMultipleServicers" name="IsMultipleServicers"> <option value="false">No</option> <option selected="selected" value="true">Yes</option> </select> </td> </tr> </table>
Note that now I get the selected option, which will be the second item in the list.
Here is my ViewModel just to bind everything together:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MVCProject.Models.ViewModels.Service { public class ServiceViewModel : ViewModel { public List<SelectListItem> IsMultipleServicers { get; set; } } }
Here is my action:
[AcceptVerbs(HttpVerbs.Get)] public virtual ActionResult Service() { return View(new ServiceViewModel() { IsMultipleServicers = BuildBooleanSelectList(true) }; } private List<SelectListItem> BuildBooleanSelectList(bool isTrue) { List<SelectListItem> list = new List<SelectListItem>(); if (isTrue) { list.Add(new SelectListItem() { Selected = false, Text = "No", Value = "false" }); list.Add(new SelectListItem() { Selected = true, Text = "Yes", Value = "true" }); } else { list.Add(new SelectListItem() { Selected = true, Text = "No", Value = "false" }); list.Add(new SelectListItem() { Selected = false, Text = "Yes", Value = "true" }); } return list; }