1

I have enumerations that I need to display in a dropdownlist, and have them pre-populated in my admin pages.

Are there any built in html helpers for this already?

(asp.net mvc)

Tad Donaghe
  • 6,640
  • 1
  • 28
  • 63
Blankman
  • 248,432
  • 309
  • 736
  • 1,161

2 Answers2

5

From How do you create a dropdownlist from an enum in ASP.NET MVC?

Given the enum

public enum Status
{ 
    Current = 1, 
    Pending = 2, 
    Cancelled = 3 
} 

And the Extension Method

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
  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();
Community
  • 1
  • 1
Robert Harvey
  • 173,679
  • 45
  • 326
  • 490
2

As a corollary to Robert Harvey's answer, using the DescriptionAttribute will allow you to handle enum values that have multiple words, e.g.:

public enum MyEnum {
  [Description("Not Applicable")]
  NotApplicable,
  Yes,
  No
}

You can grab the DescriptionAttribute value if it exists and then use descriptionAttributeText ?? enumMemberName as the display text for your drop-down.

Josh Kodroff
  • 26,051
  • 26
  • 92
  • 147