DROPDOWNLIST FROM AN ENUM IN ASP.NET MVC

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
 1428  View(s)
Ratings:
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?

  1. Takeshi Okada

    Post:89

    Points:629
    Re: Dropdownlist from an enum in ASP.NET MVC

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!