Have just started playing with ASP.NET MVC and have stumbled over the following situation. It feels a lot like a bug but if its not, an explanation would be appreciated :)
The View contains pretty basic stuff
<%=Html.DropDownList("MyList", ViewData["MyListItems"] as SelectList)%>
<%=Html.TextBox("MyTextBox")%>
When not using a model, the value and selected item are set as expected:
//works fine
public ActionResult MyAction(){
ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"}
ViewData["MyList"] = "XXX"; //set the selected item to be the one with value 'XXX'
ViewData["MyTextBox"] = "ABC"; //sets textbox value to 'ABC'
return View();
}
But when trying to load via a model, the textbox has the value set as expected, but the dropdown doesnt get a selected item set.
//doesnt work
public ActionResult MyAction(){
ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"}
var model = new {
MyList = "XXX", //set the selected item to be the one with value 'XXX'
MyTextBox = "ABC" //sets textbox value to 'ABC'
}
return View(model);
}
Any ideas? My current thoughts on it are that perhaps when using a model, we're restricted to setting the selected item on the SelectList constructor instead of using the viewdata (which works fine) and passing the selectlist in with the model - which would have the benefit of cleaning the code up a little - I'm just wondering why this method doesnt work....
Many thanks for any suggestions
Actually, you just have to pass in null
for the Html.DropDownList()
.
I was having the same exact problem, and used the Reflector to look at the MVC Source Code.
In the System.Web.Mvc.Extensions.SelectExtensions
class's SelectInternal()
method, it checks whether the selectList parameter is null or not.
If it is passed in as null
, it looks up the SelectList
properly.
Here is the "Code-behind".
ViewData["MyDropDown"] = new SelectList(selectListItems,
"Value",
"Text",
selectedValue.ToString()
);
Here is the HTML view code.
<%= Html.DropDownList("MyDropDown", null,
"** Please Select **",
new { @class = "my-select-css-class" }
) %>
Note: I'm using ASP.NET MVC 2.0 (Beta Version).
After extensively using ASP.NET MVC for the past 3 years, I prefer using additionalViewData
from the Html.EditorFor()
method more.
Pass in your [List Items] as an anonymous
object with the same property name as the Model's property into the Html.EditorFor()
method.
<%= Html.EditorFor(
m => m.MyPropertyName,
new { MyPropertyName = Model.ListItemsForMyPropertyName }
) %>
If you want more details, please refer to my answer in another thread here.