Vincular Enum com lista suspensa e definir o valor selecionado para obter ação no MVC C #

Eu tenho um Enum chamado CityType

 public enum CityType { [Description("Select City")] Select = 0, [Description("A")] NewDelhi = 1, [Description("B")] Mumbai = 2, [Description("C")] Bangalore = 3, [Description("D")] Buxar = 4, [Description("E")] Jabalpur = 5 } 

Gerar lista de Enum

 IList list = Enum.GetValues(typeof(CityType)).Cast().Select(x => new SelectListItem(){ Text = EnumHelper.GetDescription(x), Value = ((int)x).ToString() }).ToList(); int city=0; if (userModel.HomeCity != null) city= (int)userModel.HomeCity; ViewData["HomeCity"] = new SelectList(list, "Value", "Text", city); 

Vincular em .cshtml

 @Html.DropDownList("HomeCity",null,new { @style = "width:155px;", @class = "form-control" }) 

EnumHelper Classe GetDescription para obter Descrição do Enum

Eu escrevi sobre este mesmo assunto em que eu crio um EnumHelper para ajudar nessa tarefa comum.

http://jnye.co/Posts/4/creating-a-dropdown-list-from-an-enum-in-mvc-and-c%23

No seu controlador:

 //If you don't have an enum value use the type ViewBag.DropDownList = EnumHelper.SelectListFor(); //If you do have an enum value use the value (the value will be marked as selected) ViewBag.DropDownList = EnumHelper.SelectListFor(MyEnum.MyEnumValue); 

Na sua vista:

 @Html.DropDownList("DropDownList") @* OR *@ @Html.DropDownListFor(m => m.Property, ViewBag.DropDownList as SelectList, null) 

A class auxiliar:

 public static class EnumHelper { // Get the value of the description attribute if the // enum has one, otherwise use the value. public static string GetDescription(this TEnum value) { var fi = value.GetType().GetField(value.ToString()); if (fi != null) { var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) { return attributes[0].Description; } } return value.ToString(); } ///  /// Build a select list for an enum ///  public static SelectList SelectListFor() where T : struct { Type t = typeof(T); return !t.IsEnum ? null : new SelectList(BuildSelectListItems(t), "Value", "Text"); } ///  /// Build a select list for an enum with a particular value selected ///  public static SelectList SelectListFor(T selected) where T : struct { Type t = typeof(T); return !t.IsEnum ? null : new SelectList(BuildSelectListItems(t), "Text", "Value", selected.ToString()); } private static IEnumerable BuildSelectListItems(Type t) { return Enum.GetValues(t) .Cast() .Select(e => new SelectListItem { Value = e.ToString(), Text = e.GetDescription() }); } } 

Este é o código que eu uso para enums em dropdowns. Então é só usar @ Html.DropDown / For (); e coloque este SelectList como param.

 public static SelectList ToSelectList(this Type enumType, string selectedValue) { var items = new List(); var selectedValueId = 0; foreach (var item in Enum.GetValues(enumType)) { FieldInfo fi = enumType.GetField(item.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); var title = ""; if (attributes != null && attributes.Length > 0) { title = attributes[0].Description; } else { title = item.ToString(); } var listItem = new SelectListItem { Value = ((int)item).ToString(), Text = title, Selected = selectedValue == ((int)item).ToString(), }; items.Add(listItem); } return new SelectList(items, "Value", "Text", selectedValueId); } 

Além disso, você pode estender DropDownFor assim:

 public static MvcHtmlString EnumDropdownListFor(this HtmlHelper htmlHelper, Expression> expression, Type enumType, object htmlAttributes = null) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); SelectList selectList = enumType.ToSelectList(metadata.Model.ToString()); return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes); } 

O uso se parece com isso:

 @Html.EnumDropdownListFor(model => model.Property, typeof(SpecificEnum))