23

如何在 Razor 的下拉列表中显示我的枚举的自定义名称?我目前的代码是:

@Html.DropDownListFor(model => model.ExpiryStage,
        new SelectList(Enum.GetValues(typeof(ExpiryStages))),
        new { @class = "selectpicker" })

我的枚举是:

public enum ExpiryStages
{
    [Display(Name = "None")]
    None = 0,

    [Display(Name = "Expires on")]
    ExpiresOn = 1,

    [Display(Name = "Expires between")]
    ExpiresBetween = 2,

    [Display(Name = "Expires after")]
    ExpiresAfter = 3,

    [Display(Name = "Current")]
    Current = 4,

    [Display(Name = "Expired not yet replaced")]
    ExpiredNotYetReplaced = 5,

    [Display(Name = "Replaced")]
    Replaced = 6
}

例如,我想在 DropDownList 中显示“Expired NotYetReplaced”而不是 ExpiredNotYetReplaced。

4

4 回答 4

39

从 MVC 5.1 开始,他们添加了这个新的助手。你只需要一个枚举

public enum WelcomeMessageType
    {
        [Display(Name = "Prior to accepting Quote")]
        PriorToAcceptingQuote,
        [Display(Name = "After Accepting Quote")]
        AfterAcceptingQuote
    }

您可以通过编写来创建显示名称的下拉列表

@Html.EnumDropDownListFor(model => model.WelcomeMessageType, null, new { @id = "ddlMessageType", @class = "form-control", @style = "width:200px;" })
于 2015-05-21T03:39:48.167 回答
6

我有一个枚举扩展名来检索显示名称。

public static string GetDescription<TEnum>(this TEnum value)
{
    var attributes = value.GetAttributes<DescriptionAttribute>();
    if (attributes.Length == 0)
    {
       return Enum.GetName(typeof(TEnum), value);
    }

    return attributes[0].Description;
}

您可以像这样使用它:

Enum.GetValues(typeof(ExpiryStages)).Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });

我使用一个方便的助手从枚举中生成选择列表:

public static SelectList SelectListFor<T>() 
        where T : struct
{
    var t = typeof (T);

    if(!t.IsEnum)
    {
        return null;
    }

    var values = Enum.GetValues(typeof(T)).Cast<T>()
                   .Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });

    return new SelectList(values, "Id", "Name");
}
于 2013-09-11T10:42:01.150 回答
3

在 ASP.Net Core 中,可以使用 HtmlHelper 方法IHtmlHelper.GetEnumSelectList(),例如可以如下使用:

asp-items="@Html.GetEnumSelectList<MyEnumType>()"
于 2017-09-20T15:27:10.780 回答
3

您可以用于下拉 asp.net 核心

                    <select asp-for="DeliveryPolicy" asp-items="Html.GetEnumSelectList<ExpiryStages>()">
                        <option selected="selected" value="">Please select</option>
                    </select>
于 2018-03-29T21:04:23.337 回答