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:
You can then use the resulting object reference to pass to a SelectList constructor and use it within a DropDownList like this:
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)
In the view, use the ViewData item to obtain an IEnumerable object type (assuming you are using the Razor view engine):
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
@Html.DropDownListFor(mdl => mdl.VType, (IEnumerable)ViewData["VTypes"])
No comments:
Post a Comment