Thursday, August 28, 2008

ASP.NET MVC HtmlHelper DropDownList

If you've been working with ASP.NET MVC Preview 3, or later, you may have wondered how to create a drop down list.

From within your controller, you define the System.Web.Mvc.SelectList for the DropDownList. Think of the SelectList as all of the information that the html control will need to contain your list, set the text and value field, and specify the selected item.

var dbContext = new TriathlonDataContext();

var stateProvinceList = from sp in dbContext.StateProvinces
where sp.IsActive == true
orderby sp.StateProvinceCode
select sp;

ViewData["StateProvinceID"] = new SelectList(stateProvinceList.ToList(), "StateProvinceCode", "Name");


The end result is a working drop down list, like the one pictured below:


mxmissile said...

where is the "View"'s code?

Troy Hildebrand said...
This comment has been removed by the author.