I'm sure I am missing something obvious, but this is driving me nuts! If I specify html options, the value of my dropdownlist doesn't set.
In my controller, I retrieve the options for my dropdownlist with:
ViewData["Coordinator"] = new SelectList(userRepository.GetIdUserList(1), "ID", "Signature",edCenter.Coordinator);
In my view I populate the dropdownlist with:
Html.DropDownList("Coordinator",(IEnumerable) ViewData["Coordinator"], new {style="width:175px"})
The dropdown values are populated perfectly, but the value of the list isn't selected.
However, if I just use:
Html.DropDownList("Coordinator");
Everything works fine.
What is going wrong??
Best Answer
I was struggling with a similar problem yesterday so if you are still getting the same result there is one more thing to consider. The
DropDownList
sometimes ignores the selected value of yourSelectList
, it's annoying but what it does is try to get the selected value from theModelState
,ViewData
and Model by using the field name as a key. In your case you are storing the list inViewData["Coordinator"]
, the key has the same name as the DropDown. Try this:Then in the view:
If you want to see what's going on behind the curtains open reflector (or get the MVC source) and browse this method:
System.Web.Mvc.Html.SelectExtensions.SelectInternal()