- Posted by miketeye on October 8, 2011
Share on FacebookSimple extension method to convert enumeration to a selectList for use with MVC DropDownList.
public static SelectList ToSelectList(this Enum enumeration)
{
var list = (from Enum d in Enum.GetValues(enumeration.GetType())
select new { ID = (int)Enum.Parse(enumeration.GetType(), Enum.GetName(enumeration.GetType(), d)), Name = d.ToString() }).ToList();
return new SelectList(list, "ID", "Name");
}
Say you have an enumeration depicted in the code below:
public enum Options
{
option1= 1,
option2= 2,
option3=3
}
You will use the above extension in this way:
SelectList Selections;
Options opts = new Options();
Selections = opts.ToSelectList();