using System.Collections.Generic; namespace System.Web.Mvc { public static class EnumDropDownList { /// /// Creates a dropdown list from an enum /// /// name of the element /// the enum type /// public static string DropDownList(this HtmlHelper helper, string name, Type type) { return DropDownList(helper, name, type, null); } /// /// Creates a dropdown list from an enum. /// /// name of an element /// the enum type /// selected enum value /// public static string DropDownList(this HtmlHelper helper, string name, Type type, object selected) { if (!type.IsEnum) throw new ArgumentException("Type is not an enum."); if(selected != null && selected.GetType() != type) throw new ArgumentException("Selected object is not " + type.ToString()); var enums = new List(); foreach (int value in Enum.GetValues(type)) { var item = new SelectListItem(); item.Value = value.ToString(); item.Text = Enum.GetName(type, value); if(selected != null) item.Selected = (int)selected == value; enums.Add(item); } return System.Web.Mvc.Html.SelectExtensions.DropDownList(helper, name, enums); } } }