Bind Enum To DropDownList In ASP.NET MVC

Introduction

Sometimes, we have a scenario during development where we need to populate DropDownList from Enum. There are a couple of ways to do it. But every way has its pros and cons. One should always keep in mind the SOLID and DRY principle while writing code. I will show two ways to do it and you will be able to understand which one is better and why it is better.

Approach 1 (Typical Way)

The first approach in my point of view is not very elegant, but it will surely do what we want it to.

Consider the following Enum which we want to populate in the drop down:

  1. public enum eUserRole: int  
  2. {  
  3.     SuperAdmin = 0,  
  4.     PhoenixAdmin = 1,  
  5.     OfficeAdmin = 2,  
  6.     ReportUser = 3,  
  7.     BillingUser = 4  
  8. }  
So normally, what we do is create SelectList by adding each Enum value,
  1. var enumData = from eUserRole e in Enum.GetValues(typeof(eUserRole))  
  2. select new   
  3. {   
  4.    ID = (int)e,   
  5.    Name = e.ToString()   
  6. };  
Now, set it in ViewBag so that we can use it in View:
  1. ViewBag.EnumList = new SelectList(enumData,"ID","Name");  
And now in View:
  1. @Html.DropDownList("EnumDropDown",ViewBag.EnumList as SelectList)  
Problem in Approach 1

The problem with the above method is that whenever we have Enum to be bind with some HTML Helper, we have to write the above Linq query code to get the enum all values in the action which is a bit of a pain to rewrite one thing again and again. We will see next how we can make it better and reusable.

Approach 2

Now, here is an elegant way to achieve it using Extension Method and Generics, which will return us Enum values as a SelectList for any type of Enum:
  1. public static class ExtensionMethods  
  2. {  
  3.     public static System.Web.Mvc.SelectList ToSelectList < TEnum > (this TEnum obj)  
  4.     where TEnum: struct, IComparable, IFormattable, IConvertible  
  5.     {  
  6.         return new SelectList(Enum.GetValues(typeof (TEnum))  
  7.         .OfType < Enum > ()  
  8.         .Select(x => new SelectListItem  
  9.         {  
  10.             Text = Enum.GetName(typeof (TEnum), x),  
  11.             Value = (Convert.ToInt32(x))  
  12.             .ToString()  
  13.         }), "Value""Text");  
  14.     }  
  15. }  
And now, we just need to call it on any Enum in action this way:
  1. ViewBag.EnumList = eUserRole.SuperAdmin.ToSelectList();  
We can also use it directly in the View, we only have to include namespace in case it's in a separate namespace:
  1. @Html.DropDownList("EnumDropDown",eUserRole.SuperAdmin.ToSelectList())  
You will probably need to set selected value of dropdownlist in the case when user is editing record.

We can extend the extension method according to our requirements.

Overload with Selected Value Parameter

Here is the extension method overload to pass selected value in case we want to set selected value, you can write other overloads as well according to the need:
  1. public static class ExtensionMethods  
  2. {  
  3.     public static System.Web.Mvc.SelectList ToSelectList < TEnum > (this TEnum obj, object selectedValue)  
  4.     where TEnum: struct, IComparable, IFormattable, IConvertible  
  5.     {  
  6.         return new SelectList(Enum.GetValues(typeof (TEnum))  
  7.         .OfType < Enum > ()  
  8.         .Select(x => new SelectListItem  
  9.         {  
  10.             Text = Enum.GetName(typeof (TEnum), x),  
  11.             Value = (Convert.ToInt32(x))  
  12.             .ToString()  
  13.         }), "Value""Text", selectedValue);  
  14.     }  
  15. }  
And usage in View this way:
  1. @Html.DropDownList("EnumDropDownWithSelected",  
  2. eUserRole.SuperAdmin.ToSelectList((int)eUserRole.OfficeAdmin))  
Now the dropdown will have OfficeAdmin selected by default.

In most cases, we don't want to show Enum value in dropdown list instead of that we want to show user friendly term as dropdown text. For that purpose, we can write our Attribute for Enum in the following way:

Create a custom class which inherits from Attribute type:
  1. public class EnumDisplayNameAttribute: Attribute  
  2. {  
  3.     private string _displayName;  
  4.     public string DisplayName  
  5.     {  
  6.         get  
  7.         {  
  8.             return _displayName;  
  9.         }  
  10.         set  
  11.         {  
  12.             _displayName = value;  
  13.         }  
  14.     }  
  15. }  
And now use attribute on Enum:
  1. public enum eUserRole: int  
  2. {  
  3.     [EnumDisplayName(DisplayName = "Super Admin")]  
  4.     SuperAdmin = 0, [EnumDisplayName(DisplayName = "Phoenix Admin")]  
  5.     PhoenixAdmin = 1, [EnumDisplayName(DisplayName = "Office Admin")]  
  6.     OfficeAdmin = 2, [EnumDisplayName(DisplayName = "Report User")]  
  7.     ReportUser = 3, [EnumDisplayName(DisplayName = "Billing User")]  
  8.     BillingUser = 4  
  9. }  
Now, we will need to modify or write another extension method as now we need to pick value of DisplayName attribute.

We now have two extension methods, one which returns specific Enum value DisplayName Attribute value and the second which return SelectList again for Enum:
  1. public static class ExtensionMethods    
  2. {    
  3.     public static System.Web.Mvc.SelectList ToSelectList < TEnum > (this TEnum obj)    
  4.     where TEnum: struct, IComparable, IFormattable, IConvertible // correct one    
  5.     {    
  6.         return new SelectList(Enum.GetValues(typeof (TEnum))    
  7.         .OfType < Enum > ()    
  8.         .Select(x => new SelectListItem    
  9.         {    
  10.             Text = x.DisplayName(),    
  11.             Value = (Convert.ToInt32(x))    
  12.             .ToString()    
  13.         }), "Value""Text");    
  14.     }    
  15.     public static string DisplayName(this Enum value)    
  16.     {    
  17.         FieldInfo field = value.GetType()    
  18.             .GetField(value.ToString());    
  19.         EnumDisplayNameAttribute attribute = Attribute.GetCustomAttribute(field, typeof (EnumDisplayNameAttribute))    
  20.         as EnumDisplayNameAttribute;    
  21.         return attribute == null ? value.ToString() : attribute.DisplayName;    
  22.     }    
  23. }   

 Problem in Approach 2

 The second approach is much better than the first one, but there is one problem left in approach 2 which is that we have hard coded Attribute type in the extension, it is quite possible that we have multiple Enum attributes and we can have them decorated with different Enums and calling this extension method on those would not work well. 

Approach 3

So, I came up with a better implementation so that consumers can pass the attribute type and property of attribute which needs to be used.
We will add another extension method which returns the attribute value and it will be generic so user can specify the attribute type itself:
  1. public static string AttributeValue<TEnum,TAttribute>(this TEnum value,Func<TAttribute,string> func)   
  2.     where T : Attribute  
  3. {  
  4.    FieldInfo field = value.GetType().GetField(value.ToString());  
  5.   
  6.    T attribute = Attribute.GetCustomAttribute(field, typeof(T)) as T;  
  7.   
  8.    return attribute == null ? value.ToString() : func(attribute);  
  9.   
  10. }    
This extension we will consume inside the extension method which returns Enum as SelectList:
  1. public static System.Web.Mvc.SelectList ToSelectList<TEnum,TAttribute>  
  2. (this TEnum obj,Func<TAttribute,string> func,object selectedValue=null)  
  3.   where TEnum : struct, IComparable, IFormattable, IConvertible  
  4.   where TAttribute : Attribute  
  5.     {  
  6.           
  7.         return new SelectList(Enum.GetValues(typeof(TEnum)).OfType<Enum>()   
  8.              .Select(x =>   
  9.                  new SelectListItem   
  10.                  {   
  11.                     Text = x.AttributeValue<TEnum,TAttribute>(func),   
  12.                     Value = (Convert.ToInt32(x)).ToString()   
  13.                  }),   
  14.              "Value",   
  15.              "Text",  
  16.               selectedValue);  
  17.     }  
and now consumer can use it by passing the attribute and its property which to use for Display name, our View code would now look like: 
  1. @Html.DropDownList("EnumDropDownWithSelected", eUserRole.SuperAdmin.ToSelectList<eUserRole,  
  2. numDisplayNameAttribute>(attr=>attr.DisplayName,(int)eUserRole.OfficeAdmin))  
 

Up Next
    Ebook Download
    View all
    Learn
    View all