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)
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)
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();
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.