将枚举绑定到MVC 4中的DropDownList?

Keh*_*mme 25 html data-binding asp.net-mvc enums drop-down-menu

我一直在寻找将Enums绑定到DropDowns的常用方法是通过辅助方法,这对于看似简单的任务似乎有点霸道.

将Enums绑定到ASP.Net MVC 4中的DropDownLists的最佳方法是什么?

Mr.*_*kin 25

你可以这样:

@Html.DropDownListFor(model => model.Type, Enum.GetNames(typeof(Rewards.Models.PropertyType)).Select(e => new SelectListItem { Text = e }))
Run Code Online (Sandbox Code Playgroud)


Ber*_*ann 19

我认为这是唯一的(干净的)方式,这很可惜,但至少有一些选择.我建议你看一下这个博客:http://paulthecyclist.com/2013/05/24/enum-dropdown/

抱歉,这里复制太长了,但要点是他为此创建了一个新的HTML帮助方法.

所有源代码都可以在GitHub找到.

  • 在这个问题中回答了这个答案的要点:http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc与此问题的许多其他解决方案. (2认同)

Mih*_*üür 13

自MVC 5.1以来,框架支持枚举:

@Html.EnumDropDownListFor(m => m.Palette)
Run Code Online (Sandbox Code Playgroud)

显示的文字可以自定义:

public enum Palette
{
    [Display(Name = "Black & White")]
    BlackAndWhite,

    Colour
}
Run Code Online (Sandbox Code Playgroud)

MSDN链接:http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum


Keh*_*mme 10

在我的控制器中:

var feedTypeList = new Dictionary<short, string>();
foreach (var item in Enum.GetValues(typeof(FeedType)))
{
    feedTypeList.Add((short)item, Enum.GetName(typeof(FeedType), item));
}
ViewBag.FeedTypeList = new SelectList(feedTypeList, "Key", "Value", feed.FeedType);
Run Code Online (Sandbox Code Playgroud)

在我看来:

@Html.DropDownList("FeedType", (SelectList)ViewBag.FeedTypeList)
Run Code Online (Sandbox Code Playgroud)


amh*_*hed 5

PaulTheCyclist的解决方案就在现场。但是我不会使用RESX(我必须为每个新枚举添加一个新的.resx文件?)

这是我的HtmlHelper表达式:

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,
    Expression<Func<TModel, TEnum>> expression, object attributes = null)
{
    //Get metadata from enum
    var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    var enumType = GetNonNullableModelType(metadata);
    var values = Enum.GetValues(enumType).Cast<TEnum>();

    //Convert enumeration items into SelectListItems
    var items =
        from value in values
        select new SelectListItem
        {
            Text = value.ToDescription(),
            Value = value.ToString(),
            Selected = value.Equals(metadata.Model)
        };

    //Check for nullable value types
    if (metadata.IsNullableValueType)
    {
        var emptyItem = new List<SelectListItem>
        {
            new SelectListItem {Text = string.Empty, Value = string.Empty}
        };
        items = emptyItem.Concat(items);
    }

    //Return the regular DropDownlist helper
    return htmlHelper.DropDownListFor(expression, items, attributes);
}
Run Code Online (Sandbox Code Playgroud)

这是我声明枚举的方式:

[Flags]
public enum LoanApplicationType
{
    [Description("Undefined")]
    Undefined = 0,

    [Description("Personal Loan")]
    PersonalLoan = 1,

    [Description("Mortgage Loan")]
    MortgageLoan = 2,

    [Description("Vehicle Loan")]
    VehicleLoan = 4,

    [Description("Small Business")]
    SmallBusiness = 8,
}
Run Code Online (Sandbox Code Playgroud)

这是来自“剃刀视图”的调用:

<div class="control-group span2">
    <div class="controls">
        @Html.EnumDropDownListFor(m => m.LoanType, new { @class = "span2" })
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

@Model.LoanTypeLoanApplicationType类型的模型属性在哪里

更新:抱歉,忘记包含帮助函数ToDescription()的代码

/// <summary>
/// Returns Description Attribute information for an Enum value
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string ToDescription(this Enum value)
{
    if (value == null)
    {
        return string.Empty;
    }
    var attributes = (DescriptionAttribute[]) value.GetType().GetField(
        Convert.ToString(value)).GetCustomAttributes(typeof (DescriptionAttribute), false);
    return attributes.Length > 0 ? attributes[0].Description : Convert.ToString(value);
}
Run Code Online (Sandbox Code Playgroud)

  • 嗨,如果您要使用基于我的博客的解决方案,则所有枚举都只需要一个resx文件,只需使用约定来区分枚举即可。例如,如果您有两个枚举,则用颜色和数字表示。一些resx条目可能具有以下名称:Colour_Blue,Colour_Red,Colour_White,LoanApplicationType_Undefined,LoanApplicationType_Personal。尽管您的Web应用程序不需要考虑本地化,但是Description属性可以正常工作 (2认同)