Friday, August 23, 2013

Enums (Enumerations) in ASP.NET MVC DropDownLists

Getting an Enum within an ASP.NET MVC DropDownLists can be performed using reflection if you do not want to have to create the entries manually. You can get SelectListItem objects from the Enum as follows:

var listItems = from MyEnumType e in Enum.GetValues(typeof(MyEnumType))
select new SelectListItem() { Text = e.ToString(), Value = ((int)e).ToString() };

You can then use the resulting object reference to pass to a SelectList constructor and use it within a DropDownList like this:

var selLst = new SelectList(listItems, "Value", "Text");

Further, you can use it within an ASP.NET MVC DropDownList in the manner described below.

In the controller, assign it to a ViewData item (you can use a View Model instead, if you prefer)

ViewData["VTypes"] = selLst;

In the view, use the ViewData item to obtain an IEnumerable object type (assuming you are using the Razor view engine):

@Html.DropDownListFor(mdl => mdl.VType, (IEnumerable)ViewData["VTypes"])

No comments: