How To Work With Enums In ASP.NET MVC

Recently, I got a question from one of the readers that how to work with Enums in ASP.NET MVC. Before we move ahead in this post, let me tell you that it is very simple to work with Enums in ASP.NET MVC 5.1 and later. In MVC 5.1, HTML helper class EnumDropDownListFor has been introduced which is used to display the Enum in a dropdown as in the following screenshot,

Dropdown image

To start with let us consider that we created an EnumTypeOfStudent as in the following listing. This Enum holds information about the type of a particular student.

  1. public enumTypeOfStudent  
  2. {  
  3.    [Display(Name = "Science Student.")]  
  4.    SS,  
  5.    [Display(Name = "Arts Student.")]  
  6.    AS,  
  7.    [Display(Name = "Economics Student.")]  
  8.    ES,  
  9.   
  10. }  

We are going to use TypeOfStudentenum in the Student class which is created as shown in the listing below:

  1. public classStudent  
  2. {  
  3.     public int Id  
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public string Name  
  9.     {  
  10.         get;  
  11.         set;  
  12.     }  
  13.     public int Age  
  14.     {  
  15.         get;  
  16.         set;  
  17.     }  
  18.     public TypeOfStudentStudentType  
  19.     {  
  20.         get;  
  21.         set;  
  22.     }  
  23. }  
Right click on the Controller folder and create a controller using the scaffolding. We need to select MVC 5 controller using the Entity Framework as in the following screenshot,

MVC5 Controller

In the Model class select Student and create a Data context class (perhaps select an existing one) to add a controller.

add controller

We just added a controller which is using Student class as model and the Student class has EnumTypeOfStudent as a property. Let us go ahead and run the application, we will find Enum property is rendered in the dropdown as in the following screenshot:

run
We can see Enum values has been populated in the StudentType dropdown. In the Create and Edit views of the controller, a control EnumDropDownListFor has been added as in the following listing: 
  1. <divclass="form-group">   
  2.   @Html.LabelFor(model =>model.StudentType, htmlAttributes:   
  3.                  new {   
  4.                         @class = "control-label col-md-2"  
  5.                     })  
  6.     <divclass="col-md-10">   
  7.     @Html.EnumDropDownListFor(model =>model.StudentType, htmlAttributes:   
  8.                   new {   
  9.                         @class = "form-control"   
  10.                       })   
  11.     @Html.ValidationMessageFor(model =>model.StudentType, "",   
  12.                   new {  
  13.                         @class = "text-danger"   
  14.                       })   
  15.       </div>  
  16.   </div>  
When we create View using the scaffolding, MVC 5.1 and later use HTML Helper class EnumDropDownListFor to create dropdown from the Enum.

Using RadioButtons for the Enum

In MVC 5.1 onwards we do have support of EnumDropDownListFor which renders Enum values to a drop down. We may have a requirement to render the Enum values to RadioButton. There is no simple way to do it. For this we have to create HTML Helper class. Let us go ahead and create a HTML helper class. To create HTML Helper class: 
  1. Add a static class to the project.
  2. Add HTML Helper method as static method to the class.

I have created a folder named Helper and inside that created a class EnumRadioButtonHelper. Inside the static class, we have created static method EnumRadioButton to render Enums in the RadioButtons.

  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.ComponentModel.DataAnnotations;  
  4. usingSystem.Linq;  
  5. usingSystem.Linq.Expressions;  
  6. usingSystem.Text;  
  7. usingSystem.Threading.Tasks;  
  8. usingSystem.Web;  
  9. usingSystem.Web.Mvc;  
  10. using System.Web.Mvc.Html;  
  11. namespaceMVCEnum.Helper  
  12. {  
  13.     publicstaticclassEnumRadioButtonHelper  
  14.     {  
  15.         publicstaticMvcHtmlStringEnumRadioButton < TModel, TProperty > (thisHtmlHelper < TModel > htmlHelper, Expression < Func < TModel, TProperty >> expression)  
  16.         {  
  17.             varmetaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);  
  18.             varlistOfValues = Enum.GetNames(metaData.ModelType);  
  19.             varsb = newStringBuilder();  
  20.             if (listOfValues != null)  
  21.             {  
  22.                 sb = sb.AppendFormat("<ul>");  
  23.                 foreach(var name inlistOfValues)  
  24.                 {  
  25.                     var label = name;  
  26.                     varmemInfo = metaData.ModelType.GetMember(name);  
  27.                     if (memInfo != null)  
  28.                     {  
  29.                         var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);  
  30.                         if (attributes != null && attributes.Length > 0) label = ((DisplayAttribute) attributes[0]).Name;  
  31.                     }  
  32.                     var id = string.Format("{0}_{1}_{2}", htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, metaData.PropertyName, name);  
  33.                     var radio = htmlHelper.RadioButtonFor(expression, name, new  
  34.                     {  
  35.                         id = id  
  36.                     }).ToHtmlString();  
  37.                     sb.AppendFormat("<li>{0}{1}</li>", radio, HttpUtility.HtmlEncode(label));  
  38.                 }  
  39.                 sb = sb.AppendFormat("</ul>");  
  40.             }  
  41.             returnMvcHtmlString.Create(sb.ToString());  
  42.         }  
  43.     }  
  44. }  
We can use the EnumRadioButton helper method on the view directly. We also need to make sure we have added the namespace of the helper class on the view. I have added the namespace as in the following listing: 
  1. @usingMVCEnum.Helper  
  2. @model MVCEnum.Models.Student  
Once namespace is added, EnumRadioButton can be used to render Enum in RadioButton as in the following listing: 
  1. <divclass="form-group"
  2. @Html.LabelFor(model =>model.StudentType, htmlAttributes: 
  3. new { 
  4.       @class = "control-label col-md-2" 
  5.      })  
  6.     <divclass="col-md-10"> @Html.EnumRadioButton(m =>m.StudentType) </div>  
  7. </div>
On running the application, we will find StudentType is rendered in RadioButton as in the following listing:

Create

We learnt how to work with Enums in MVC 5.1 and later. In MVC 5.1 EnumDropDownListFor has been introduced to render Enums in DropDown. We can also create HTML helper class to render Enums in RadioButtons. I hope you find this post useful. Thanks for reading.