Hi folks, I am new to Asp.Net MVC. I was trying to populate a dropdown from an Enum.
After searching on web couldn’t realy find a direct solution, so thought to do in my own way and finally got this solution.
Now here is an excertp from my code.
MyEmun is the Enum from which I want to populate the dropdown.
public enum MyEnum
{
Day = 1 ,
Month = 2,
Year = 3
}
MyEnumList() is a function that return a collection of SelectListItem that is used to populate the Dropdown.
private IList<SelectListItem> MyEnumList()
{
string[] names = Enum.GetNames(typeof(MyEnum));
Array values = Enum.GetValues(typeof(MyEnum));
IList<SelectListItem> items = new List<SelectListItem>();
for (int i = 0; i < names.Length; i++)
{
int val = (int)values.GetValue(i);
items.Add(new SelectListItem
{
Text = names[i],
Value = val.ToString()
});
}
return items;
}
Pass the return value of MyEnumList() using ViewData from your controller to the view where you have the dropdown
ViewData[“MyList”] = MyEnumList ();
And finally populate your dropdown
<%=Html.DropDownList(“MyDropDown”,new SelectList((IList)ViewData[“MyList “],”Value”,”Text”))%>
hope this would helps 🙂