I\'m trying to use the Html.DropDownList
extension method but can\'t figure out how to use it with an enumeration.
Let\'s say I have an enumeration like
This is Rune & Prise answers altered to use the Enum int
value as the ID.
Sample Enum:
public enum ItemTypes
{
Movie = 1,
Game = 2,
Book = 3
}
Extension method:
public static SelectList ToSelectList(this TEnum enumObj)
{
var values = from TEnum e in Enum.GetValues(typeof(TEnum))
select new { Id = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
return new SelectList(values, "Id", "Name", (int)Enum.Parse(typeof(TEnum), enumObj.ToString()));
}
Sample of usage:
<%= Html.DropDownList("MyEnumList", ItemTypes.Game.ToSelectList()) %>
Remember to Import the namespace containing the Extension method
<%@ Import Namespace="MyNamespace.LocationOfExtensionMethod" %>
Sample of generated HTML:
Note that the item that you use to call the ToSelectList
on is the selected item.