Click here to Skip to main content
15,886,808 members
Articles / Web Development / ASP.NET
Article

Creating a DropDownList for Enums in ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.74/5 (27 votes)
3 Oct 2013CPOL2 min read 159.1K   31   18
This article explains how to populate a DropDownList by enum type in ASP.NET MVC.

Table of Contents

Introduction

I will be using two approaches to populate a DropDownList. The first one is simple in which I populate the DropDownList by an enum using SelectListItem while in the other approach, I create an HTML Helper method to populate the DropDownList. Let's see each one.

Create an enum, ActionType, under the Models folder, as in the following code snippet.

C#
namespace DropdownExample.Models
{
    public enum ActionType
    {
        Create=1,
        Read=2,
        Update=3,
        Delete=4
    }
}

Approach 1: Populate DropDownList by SelecteListItem using Enum

I populate the DropDownList using a SelectListItem type list. So we need to first create a list from an enum and thereafter that list binds with the DropDownListFor method of the HTML Helper class on the view. Create a model (ActionModel class) under the Models folder.

C#
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace DropdownExample.Models
{
    public class ActionModel
    {
        public ActionModel()
        {
            ActionsList = new List<SelectListItem>();
        }
        [Display(Name="Actions")]
        public int ActionId { get; set; }
        public IEnumerable<SelectListItem> ActionsList { get; set; }       
    }
}

Now create a controller action method in the Action Controller (ActionController.cs) that returns a view that binds with the model.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using DropdownExample.Models;
namespace DropdownExample.Controllers
{
    public class ActionController : Controller
    {
        public ActionResult Index()
        {
            ActionModel model = new ActionModel();
            IEnumerable<ActionType> actionTypes = Enum.GetValues(typeof(ActionType))
                                                       .Cast<ActionType>();
            model.ActionsList = from action in actionTypes
                                select new SelectListItem
                                {
                                    Text = action.ToString(),
                                    Value = ((int)action).ToString()
                                };
            return View(model);
        }
    }
}

Create a View (Index.cshtml) under the subfolder Action under the Views folder.

HTML
@model DropdownExample.Models.ActionModel
@{
    ViewBag.Title = "Index";
} 
@Html.LabelFor(model=>model.ActionId)
@Html.DropDownListFor(model=>model.ActionId, Model.ActionsList)

Run the application and we get the results as in Figure 1.1.

Output screen

Figure 1.1 Populate DropDownList by Enums

Approach 2: Populate the DropDownList by HTML Helper method for the Enum

I create an HTML Helper extension method to populate a dropdown list using an enum. Create an extension method EnumDropDownListFor in the Extension class under the Models folder.

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html; 
namespace DropdownExample.Models
{
    public static class Extension
    { 
        public static MvcHtmlString EnumDropDownListFor<TModel, TProperty, TEnum>(
                    this HtmlHelper<TModel> htmlHelper,
                    Expression<Func<TModel, TProperty>> expression, 
                    TEnum selectedValue)
        {
            IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum))
                                        .Cast<TEnum>(); 
            IEnumerable<SelectListItem> items = from value in values
                                                select new SelectListItem()
                                                {
                                                    Text = value.ToString(),
                                                    Value = value.ToString(),
                                                    Selected = (value.Equals(selectedValue))
                                                }; 
            return SelectExtensions.DropDownListFor(htmlHelper,expression, items);
        }
    }
}

Create a model (ActionTypeModel class) under the Models folder.

C#
using System.ComponentModel.DataAnnotations;
namespace DropdownExample.Models
{
    public class ActionTypeModel
    {
        [Display(Name = "Actions")]
        public int ActionId { get; set; }
        public ActionType ActionTypeList { get; set; }
    }
}

Now create a controller action method ActionTypes() in the Action Controller (ActionController.cs) that returns a view that binds with the model.

C#
public ActionResult ActionTypes()
{
     ActionTypeModel model = new ActionTypeModel();
     return View(model);
}

Create a View (ActionTypes.cshtml) under the subfolder Action under the Views folder.

C#
@model DropdownExample.Models.ActionTypeModel
@using DropdownExample.Models;
@{
    ViewBag.Title = "Action Types";
}
@Html.LabelFor(model => model.ActionId)
@Html.EnumDropDownListFor(model => model.ActionId,Model.ActionTypeList)

Run the application and we get the same result as in Figure 1.1.

Conclusion

Finally we have created an HTML helper extension method for a dropdown list that populates by enum type.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
He is awarded for Microsoft TechNet Guru, CodeProject MVP and C# Corner MVP. http://l-knowtech.com/

Comments and Discussions

 
GeneralSimple, clear Pin
zamkinos30-Sep-15 19:40
zamkinos30-Sep-15 19:40 
GeneralMy vote of 4 Pin
Member 1083393027-May-14 4:59
Member 1083393027-May-14 4:59 
GeneralRe: My vote of 4 Pin
Sandeep Singh Shekhawat30-Aug-14 16:53
professionalSandeep Singh Shekhawat30-Aug-14 16:53 
Questiongreat work - how about adding HTML attributes ? Pin
SteveMintz24x719-May-14 5:08
SteveMintz24x719-May-14 5:08 
AnswerRe: great work - how about adding HTML attributes ? Pin
Sandeep Singh Shekhawat30-Aug-14 16:56
professionalSandeep Singh Shekhawat30-Aug-14 16:56 
QuestionCompiler errors Pin
pkfox20-Mar-14 7:33
professionalpkfox20-Mar-14 7:33 
AnswerRe: Compiler errors Pin
Sandeep Singh Shekhawat30-Aug-14 16:57
professionalSandeep Singh Shekhawat30-Aug-14 16:57 
GeneralRe: Compiler errors Pin
pkfox30-Aug-14 22:13
professionalpkfox30-Aug-14 22:13 
GeneralRe: Compiler errors Pin
Sandeep Singh Shekhawat7-Nov-14 21:37
professionalSandeep Singh Shekhawat7-Nov-14 21:37 
QuestionMVC Dot Net Pin
Member 387298112-Mar-14 21:21
Member 387298112-Mar-14 21:21 
AnswerRe: MVC Dot Net Pin
Sandeep Singh Shekhawat30-Aug-14 17:01
professionalSandeep Singh Shekhawat30-Aug-14 17:01 
QuestionSelected Enum value in Approach 2? Pin
Member 236524510-Feb-14 7:57
Member 236524510-Feb-14 7:57 
AnswerRe: Selected Enum value in Approach 2? Pin
Sandeep Singh Shekhawat7-Nov-14 20:48
professionalSandeep Singh Shekhawat7-Nov-14 20:48 
QuestionMy Vote of 5 Pin
David Apomah11-Dec-13 0:00
David Apomah11-Dec-13 0:00 
AnswerRe: My Vote of 5 Pin
Sandeep Singh Shekhawat7-Nov-14 20:47
professionalSandeep Singh Shekhawat7-Nov-14 20:47 
GeneralMy vote of 5 Pin
Subeer Haldar11-Nov-13 5:30
Subeer Haldar11-Nov-13 5:30 
GeneralRe: My vote of 5 Pin
Sandeep Singh Shekhawat11-Nov-13 17:12
professionalSandeep Singh Shekhawat11-Nov-13 17:12 
GeneralAnother way out Pin
-Dr_X-8-Oct-13 9:41
-Dr_X-8-Oct-13 9:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.