Enum support in ASP.NET MVC 5.1

Table of Content

  1. Introduction
  2. Pre-requisite
  3. Software Requirement
  4. Updating current ASP.Net MVC current version to version 5.1.2
  5. Defining Enum
  6. Defining Model class
  7. Adding Action method in controller
  8. Implementing Enum helper in view
  9. Summary

Introduction

Prior to MVC 5.1 update when we have need to bind enum values in dropdown then we have to do it manually i.e. by creating Enumerable collection object from Enum values and then convert Enum collection to Collection of SelectListItem (IEnumerablee<SelectListItem>) and finally passing this collection to @html.DropDownListFor helper method to render drop-down list displaying enum values.

Now in MVC 5.1 we have new EnumDropDownListFor HTML helper method to do all this just in a line of code. Here you may refer other available feature in this version ASP.NET MVC 5.1 Release Note. 

So, rest of the article will explain how to use EnumDropDownListFor helper method to bind Enum in drop-down. Here is the magical line.

@Html.EnumDropDownListFor(model => model.EnumTypeProperty)

Pre-Requisite

This article assumes that readers have a basic understanding of ASP.Net MVC and how to work with MVC.

Software requirement

  • Visual Studio 2012: Download ASP.NET and Web Tools 2013.1 for Visual Studio 2012.
  • Visual Studio 2013: Download Visual Studio 2013 Update 1

Update ASP.Net MVC current version to version 5.1.2

When you create a new MVC project using visual studio 2013, It will create MVC project with version 5.0.0. You can verify the current version of your MVC by right clicking on System.Web.MVC assembly under references and selecting properties. Refer below snapshot.

Checking current version of MVC

Now If your current version of MVC 5.0.0 or lower, then you need to update it to version 5.1.2. Follow below steps to get required version of ASP.NET MVC.

    • Go to Tools -> NuGet Package Manager -> Package Manager Console
    • Execute below command in package manager console
Install-Package Microsoft.AspNet.Mvc -Version 5.1.2

Installing latest asp.net mvc package from nuget package manager console

This command will install the desired version of ASP.NET MVC.

Now we are ready to proceed further. 

Defining Enum

Moving ahead define a class DifficultyLevels that will represent Enum. Below code snippet defines enum DifficultyLevels.

public enum DifficultyLevels
    {
        Beginner,
        Intermediate,
        Advance,
        Proficient,
        Expert
    }

Defining Model class

Now define a model class that contains property of DifficultyLevels type. Below class CourseDTO defines Level property of type DifficultyLevels. 

    public class CourseDTO
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public DateTime PublishedDate { get; set; }
        public string Publisher { get; set; }
        public DifficultyLevels Level { get; set; }
    }

Adding Action method in controller

Now Add action method in a controller that initializes the CourseDTO model and pass this model to view. Below code snippet defines EnumDemo() action method that initializes the CourseDTO model.

public ActionResult EnumDemo()
        {
            return View( new CourseDTO 
                { 
                    Id=1,
                    Name="Whats new in ASP.Net MVC 5",
                    Author="Ashish Shukla",
                    Publisher = "Modern Pathshala",
                    PublishedDate = DateTime.Now,
                    Level = DifficultyLevels.Intermediate
                });
        }

Implementing Enum helper in view

Now finally use EnumDropDownListFor HTML helper to bind dropdown list with Enum fields. EnumDropdonListFor is strongly typed helper method. So we need to pass Enum type model property to pass as a lambda expression in order to bind Enum in drop-down list. Below line of code will populate enum as drop-down.

@Html.EnumDropDownListFor(model => model.Level)

Below is the complete code of EnumDemo.cshtml view that implement EnumDropDownListFor helper method.

@model ModernPathshala_DemoApplication.Controllers.CourseDTO

@{
    ViewBag.Title = "View1";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>EnumDropDownListFor Demo</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>CourseDTO</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Author, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Author)
                @Html.ValidationMessageFor(model => model.Author)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PublishedDate, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PublishedDate)
                @Html.ValidationMessageFor(model => model.PublishedDate)
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Publisher, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Publisher)
                @Html.ValidationMessageFor(model => model.Publisher)
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.Level, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EnumDropDownListFor(model => model.Level)
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>

Below snapshot shows the level dropdown control populated using EnumDropDownListFor helper method.

EnumDropDownListFor helper running demo

Note the value for Level will be automatically displayed selected that we initialized in the model, in our case it is Intermediate.

Summary

In this article, we saw how to bind drop-down list from enum using new EnumDropDownListFor HTML helper in new MVC framework. We keep on posting in new features of MVC. Subscribe below to get weekly updates.

Article tagged as
Author
Author: Ashish Shukla
Published On: 27/09/2015
Last revised On: 14/11/2015
View all articles by Ashish Shukla

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media