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 shown in the image below:

image

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


public enum TypeOfStudent
    {
        [Display(Name = "Science Student.")]
        SS,
        [Display(Name = "Arts Student.")]
        AS,
        [Display(Name = "Economics Student.")]
        ES,

    }

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


  public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public TypeOfStudent StudentType { get; set;}
    }

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 shown in the image below:

image

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

image

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

image

As we see that 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 shown in the listing below:


  <div class="form-group">;
            @Html.LabelFor(model =&gt; model.StudentType, htmlAttributes: new { @class = "control-label col-md-2" })
            &lt;div class="col-md-10"&gt;
                @Html.EnumDropDownListFor(model =&gt; model.StudentType, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model =&gt; model.StudentType, "", new { @class = "text-danger" })
            </div>;
        </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 RadiButtons 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.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MVCEnum.Helper
{
   public static class EnumRadioButtonHelper
    {
        public static MvcHtmlString EnumRadioButton<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);

            var listOfValues = Enum.GetNames(metaData.ModelType);

            var sb = new StringBuilder();

            if (listOfValues != null)
            {
                sb = sb.AppendFormat("<ul>");

                
                foreach (var name in listOfValues)
                {
                    var label = name;

                    var memInfo = metaData.ModelType.GetMember(name);

                    if (memInfo != null)
                    {
                        var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);

                        if (attributes != null && attributes.Length > 0)
                            label = ((DisplayAttribute)attributes[0]).Name;
                    }

                    var id = string.Format(
                        "{0}_{1}_{2}",
                        htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                        metaData.PropertyName,
                        name
                    );

                    var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();

                    sb.AppendFormat("<li>{0}{1}</li>", radio, HttpUtility.HtmlEncode(label));
                }

                sb = sb.AppendFormat("</ul>");
            }

            return MvcHtmlString.Create(sb.ToString());
        }
    }
}

We can use the EnumRadioButton helper method on the view directly. We also need to make sure that, we have added the namespace of the helper class on the view. I have added the namespace as shown in the listing below:

@using MVCEnum.Helper
@model MVCEnum.Models.Student

Once namespace is added, EnumRadioButton can be used to render Enum in RadioButton as shown in the listing below:

  <div class="form-group">
            @Html.LabelFor(model => model.StudentType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">            
                @Html.EnumRadioButton(m => m.StudentType)
            </div>
        </div>

On running the application, we will find StuentType is rendered in RadioButton also as shown in the image below:

image

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s