How to get the values of an enum into a SelectList
Solution 1:
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);
Solution 2:
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)
Solution 3:
This is what I have just made and personally I think its sexy:
public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
{
return (Enum.GetValues(typeof(T)).Cast<T>().Select(
enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
}
I am going to do some translation stuff eventually so the Value = enu.ToString() will do a call out to something somewhere.