Using Html.DropDownList in ASP.NET MVC
Posted by Jason on December 9, 2008 at 3:07 pm
This is something I think is particularly poorly documented for the MVC framework. It took me a long time Googling and, in the end, guessing in order to get it to work correctly (and it’s still not how I’d like it, but there you go). Simply put, this is the code in the Controller:
-
var portfolioSelect = new Dictionary<string, object>();
-
foreach (var portfolio in portfolioList)
-
{
-
portfolioSelect.Add(portfolio.ID, portfolio.Name);
-
}
-
ViewData["PortfolioSelectDropDownList"] = new SelectList(portfolioSelect, "key", "value", id);
And this is the code in the View:
-
<%=Html.DropDownList("PortfolioSelectDropDownList")%>
I know it’s still only in Beta, but I think it’s time some of the Microsoft boys tidied up their otherwise useful blogs to remove and update many incorrect usage instructions for the latest cut of the framework. After all, it’s the only documentation we have at the moment.
One more issue I’ve found is the name that is assigned to the resulting <select> tag. It’s a bit irritating as I may not want the name to be the same is the key that is used in the ViewData (which is what it uses here, i.e. “PortfolioSelectDropDownList” in my case). That messes up my typed view. The only way I’ve found around this is to use the name of the variable in my typed view for the ViewData key, e.g. “Project.PortfolioID”. The result is that I get a select list and when the form is posted back my Project object is populated with the selected value.
To be honest it has a certain elegance to it so it may even be the intended usage! Still seems a bit strange to me though…