【问题标题】:Display name of enum dropdownlist in RazorRazor 中枚举下拉列表的显示名称
【发布时间】:2013-09-15 08:05:08
【问题描述】:

如何在 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。

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

  • 为了搜索者的利益,您必须使用[Display(Name="...")]。 [Description("...")] 不适用于 EnumDropDownListFor
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      你可以使用下拉 asp.net core

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 2021-08-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多