Home > DeveloperSection > Forums > Dropdownlist from an enum in ASP.NET MVC
Jayden Bell
Jayden Bell

Total Post:105

Points:739
Posted on    November-18-2014 3:21 AM

 ASP.NET MVC Mvc  Dropdown 
Ratings:


 1 Reply(s)
 1140  View(s)
Rate this:

I'm trying to use the Html.DropDownList extension method but can't figure out how to use it with an enumeration.

Let's say I have an enumeration like this:

public enum ItemTypes

{

    Movie = 1,

    Game = 2,

    Book = 3

}

How do I go about creating a dropdown with these values using the Html.DropDownList extension method? Or is my best bet to simply create a for loop and create the html elements manually?



Takeshi Okada
Takeshi Okada

Total Post:89

Points:629
Posted on    November-18-2014 6:09 AM

I rolled Rune's answer into an extension method:

namespace MyApp.Common

{

    public static class MyExtensions{

        public static SelectList ToSelectList<TEnum>(this TEnum enumObj)

            where TEnum : struct, IComparable, IFormattable, IConvertible

        {

            var values = from TEnum e in Enum.GetValues(typeof(TEnum))

                select new { Id = e, Name = e.ToString() };

            return new SelectList(values, "Id", "Name", enumObj);

        }

    }

}

This allows you to write:

ViewData["taskStatus"] = task.Status.ToSelectList();

by using MyApp.Common


Don't want to miss updates? Please click the below button!

Follow MindStick