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
In ASP.NET MVC 5.1, they added the EnumDropDownListFor()
helper, so no need for custom extensions:
Model:
public enum MyEnum
{
[Display(Name = "First Value - desc..")]
FirstValue,
[Display(Name = "Second Value - desc...")]
SecondValue
}
View:
@Html.EnumDropDownListFor(model => model.MyEnum)
Using Tag Helper (ASP.NET MVC 6):
<select asp-for="@Model.SelectedValue" asp-items="Html.GetEnumSelectList<MyEnum>()">
Another fix to this extension method - the current version didn't select the enum's current value. I fixed the last line:
public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "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())).ToString());
}
You can also use my custom HtmlHelpers in Griffin.MvcContrib. The following code:
@Html2.CheckBoxesFor(model => model.InputType) <br />
@Html2.RadioButtonsFor(model => model.InputType) <br />
@Html2.DropdownFor(model => model.InputType) <br />
Generates:
https://github.com/jgauffin/griffin.mvccontrib
This is version for Razor:
@{
var itemTypesList = new List<SelectListItem>();
itemTypesList.AddRange(Enum.GetValues(typeof(ItemTypes)).Cast<ItemTypes>().Select(
(item, index) => new SelectListItem
{
Text = item.ToString(),
Value = (index).ToString(),
Selected = Model.ItemTypeId == index
}).ToList());
}
@Html.DropDownList("ItemTypeId", itemTypesList)
@Html.DropdownListFor(model=model->Gender,new List<SelectListItem>
{
new ListItem{Text="Male",Value="Male"},
new ListItem{Text="Female",Value="Female"},
new ListItem{Text="--- Select -----",Value="-----Select ----"}
}
)
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<TEnum>(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:
<select id="MyEnumList" name="MyEnumList">
<option value="1">Movie</option>
<option selected="selected" value="2">Game</option>
<option value="3">Book </option>
</select>
Note that the item that you use to call the ToSelectList
on is the selected item.