在Razor中显示枚举下拉列表的名称

时间:2013-09-11 10:32:15

标签: c# asp.net asp.net-mvc razor enums

如何在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 not yet changed”而不是ExpiredNotYetReplaced。

4 个答案:

答案 0 :(得分:34)

从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;" })

答案 1 :(得分:4)

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

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");
}

答案 2 :(得分:1)

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

asp-items="@Html.GetEnumSelectList<MyEnumType>()"

答案 3 :(得分:1)

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

                    <select asp-for="DeliveryPolicy" asp-items="Html.GetEnumSelectList<ExpiryStages>()">
                        <option selected="selected" value="">Please select</option>
                    </select>