使用下拉列表绑定枚举并在MVC C#中的get动作中设置选定值

Sat*_*ngh 6 c# asp.net-mvc enums razor

Enum有个叫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
    }
Run Code Online (Sandbox Code Playgroud)

从枚举生成列表

IList<SelectListItem> list = Enum.GetValues(typeof(CityType)).Cast<CityType>().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);
Run Code Online (Sandbox Code Playgroud)

绑定.cshtml

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

EnumHelper GetDescription类获取Enum的描述

The*_*yer 2

这是我在下拉列表中用于枚举的代码。然后只需使用 @Html.DropDown/For(); 并将此 SelectList 作为参数放入。

public static SelectList ToSelectList(this Type enumType, string selectedValue)
    {
        var items = new List<SelectListItem>();
        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);
    }
Run Code Online (Sandbox Code Playgroud)

你也可以像这样扩展 DropDownFor :

public static MvcHtmlString EnumDropdownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> 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);
    }
Run Code Online (Sandbox Code Playgroud)

用法如下:

@Html.EnumDropdownListFor(model => model.Property, typeof(SpecificEnum))
Run Code Online (Sandbox Code Playgroud)