views:

82

answers:

3

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)

+5  A: 

From http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc/694361#694361

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();
Robert Harvey
is there a way to put the ID value in the select options value attribute, instead of the text?
Blankman
If I understand you correctly: `return new SelectList(values, "Id", "Id", enumObj);`
Robert Harvey
Tried that, it is still showing option value=current, I want value=1
Blankman
+2  A: 

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
A: 

Hi can you explain how the description attribute is implemented?

Eddie