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,625
  • 1
  • 29
  • 64
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

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
  • 178,213
  • 47
  • 333
  • 501
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
  • 27,301
  • 27
  • 95
  • 148