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 :)<
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.