Creating dropdown list from Enum in ASP.NET MVC

10 Jun 2016

Enum is a data type consisting of a set of named values called elements, members, enumeral, or enumerators of the type. This is widely used in application libraries to define application status or Response status or Error status so on.,

It allows the developer to 

  1. avoid hard coding the values at different places
  2. have a meaningful name to the values

e.g., you can have a contest entry status as follows

public enum EntryStatus
{
  Approved = 1,
  Pending = 2,
  Rejected = 3
}

Rather than Hard-coding value "1", "2", "3" in the code, a developer can use following

if(currentEntry.Status == EntryStatus.Approved)
{
  //Do approval flow
}
else if(currentEntry.Status == EntryStatus.Rejected)
{
  // Rejected entry flow
}
else
{
  // Pending entry flow
}

cool Above code is more clear and meaningful.

So you can see that the values are of enumeration type and it should be possible for us to use it to generate any list.

In most cases, we would need the values to be shown in a Dropdown /Select control to allow the administrator to set a status. For rendering this enum into an HTML select element, we can use following methods based on the MVC framework that you have targeted in your solution

For MVC v5.1, you can use Html.EnumDropDownListFor

@Html.DropDownList("EntryStatus", Html.GetEnumSelectList(typeof(EntryStatus)) , "Select Status", new { @class = "form-control" });

For MVC v5 use EnumHelper

@Html.DropDownList("EntryStatus", EnumHelper.GetSelectList(typeof(EntryStatus)) , "Select My Type", new { @class = "form-control" });

For MVC < v5

You have to resort to custom MVC helper extension like this one shown below

public static class MyExtensions{
   public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
            where TEnum : struct, IComparable, IFormattable, IConvertible
   {
      var values = from TEnum e in Enum.GetValues(typeof(TEnum))
                select new { Id = e, Name = e.ToString() };
      return new SelectList(values, "Id", "Name", enumObj);
   }
}