Imagine I have an enumeration such as this (just as an example):
public enum Direction{
Horizontal = 0,
Vertical = 1,
Diagonal = 2
}
It's been awhile since I've had to do this, but I think this should work.
var directions = from Direction d in Enum.GetValues(typeof(Direction))
select new { ID = (int)d, Name = d.ToString() };
return new SelectList(directions , "ID", "Name", someSelectedValue);
I had many enum Selectlists and, after much hunting and sifting, found that making a generic helper worked best for me. It returns the index or descriptor as the Selectlist value, and the Description as the Selectlist text:
Enum:
public enum Your_Enum
{
[Description("Description 1")]
item_one,
[Description("Description 2")]
item_two
}
Helper:
public static class Selectlists
{
public static SelectList EnumSelectlist<TEnum>(bool indexed = false) where TEnum : struct
{
return new SelectList(Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(item => new SelectListItem
{
Text = GetEnumDescription(item as Enum),
Value = indexed ? Convert.ToInt32(item).ToString() : item.ToString()
}).ToList(), "Value", "Text");
}
// NOTE: returns Descriptor if there is no Description
private static string GetEnumDescription(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
Usage: Set parameter to 'true' for indices as value:
var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>();
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true);
There is a new feature in ASP.NET MVC 5.1 for this.
http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum
@Html.EnumDropDownListFor(model => model.Direction)
Or:
foreach (string item in Enum.GetNames(typeof(MyEnum)))
{
myDropDownList.Items.Add(new ListItem(item, ((int)((MyEnum)Enum.Parse(typeof(MyEnum), item))).ToString()));
}
In ASP.NET Core MVC this is done with tag helpers.
<select asp-items="Html.GetEnumSelectList<Direction>()"></select>
To get the value of an enum you need to cast the enum to its underlying type:
Value = ((int)i).ToString();