A collection of HTML helpers that generate DropDownlists for enums, with or without localization support.
Table of contents
- HTML Helpers Overview
- Some examples – Basic usage
- More examples – Localization support
- References
- Downloads
HTML Helpers Overview
I’ve created a set of HTML helpers that generate a DropDownList for an enum.
Those helpers are similar to DropDownList Method and DropDownListFor Method, with the only difference being that the those helpers will populate the DropDownList with the elements of the specified enum.
Some examples – Basic usage
Let’s assume the following model:
public enum WeekDay { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } public class WeeklyEvent { public string Title { get; set; } public WeekDay Day { get; set; } public WeekDay? AnotherDay { get; set; } }
Setting the name of the element and default empty item text
This is the most basic usage, the generated text will be enumValue.ToString():
// name="eventDay" @Html.EnumDropDownList<WeekDay>("eventDay", "Select an item") // name="Day" @Html.EnumDropDownListFor<WeeklyEvent, WeekDay>(x => x.Day, "Select an item")
Html.EnumDropDownListFor works with nullables too:
@Html.EnumDropDownListFor<WeeklyEvent, WeekDay?>(x => x.AnotherDay, "Select an item")
Using [Description] attribute
You can customize the text using DescriptionAttribute:
public enum WeekDay { [Description("Domingo")] Sunday, [Description("Segunda")] Monday, [Description("Terça")] Tuesday, [Description("Quarta")] Wednesday, [Description("Quinta")] Thursday, [Description("Sexta")] Friday, [Description("Sábado")] Saturday }
Using custom HTML attributes
Just like DropDownList and DropDownListFor, you can use custom HTML attributes
@Html.EnumDropDownList<WeekDay>("eventDay", "Select an item", new { @class="select"}) @Html.EnumDropDownListFor<WeeklyEvent, WeekDay>(x => x.Day, "Select an item" , new { @class="select"})