Tag Archives: Enum in MVC

Bind DropdownList box from the Enum values in MVC4

Yesterday i need to bind a DropDownList control with the Enum type. I have been using the html.DropDownList(name as string, IEnumerable <SelectListItem > ) method to bind show the list of the items but this method need the IEnumerable <SelectListItem > and i have a Enum type. Suppose you have a Enumeration in your model like this:

 Public Enum DepartmentList
    End Enum

You can not use this statement, it will gives an error: ‘DepartmentList is the type in model you can use as expression

  <%-- This is the Wrong way -->
   <%: Html.DropDownList("test", Model.DepartmentList)%>

So i discover a way to change the Enum type in the array and then cast in to SelectList. And you can do that in a single statement like as:

Select Department: @Html.DropDownList("lstdepartment", 
                   new SelectList(Enum.GetValues

To Retrieves an array of the values of the constants in a enumeration, we can use the Enum.GetValues() method.