选择HTML帮助程序获取扩展方法而不是枚举字符串

时间:2019-05-14 08:10:55

标签: asp.net-core enums attributes selectlist

我创建了一个枚举扩展名:

using System;
using System.ComponentModel;

namespace Shared.Enums.Extensions
{
    public static class EnumExtensions {

        // This extension method is broken out so you can use a similar pattern with 
        // other MetaData elements in the future. This is your base method for each.
        public static T GetAttribute<T>(this Enum value) where T : Attribute {
            var type = value.GetType();
            var memberInfo = type.GetMember(value.ToString());
            var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
            return attributes.Length > 0 
                ? (T)attributes[0]
                : null;
        }

        // This method creates a specific call to the above method, requesting the
        // Description MetaData attribute.
        public static string ToName(this Enum value) {
            var attribute = value.GetAttribute<DescriptionAttribute>();
            return attribute == null ? value.ToString() : attribute.Description;
        }

    }
}

这使我可以向枚举成员添加属性,以便可以使用ToName()扩展方法获得格式正确的字符串,以向用户表示emum:

    public enum Rarity
    {
        [Description("One of a kind")]
        OneOfAKind,
        [Description("Rare Item")]
        RareItem
    }

// Then in my razor view

<dt>
    @Html.DisplayNameFor(model => model.Rarity)
</dt>
<dd>
    @Model.Rarity.ToName()
</dd>

哪个很棒!

所以我希望在选择下拉列表中使用此描述。 但是似乎无法找到使用HTML.Helpers在Razor视图中实现此目标的方法。调用ToName()扩展方法的逻辑应该放在哪里?

<div class="form-group">
    <label asp-for="Rarity" class="control-label"></label>
    <select asp-for="Rarity"
       asp-items="Html.GetEnumSelectList<Rarity>()" class="form-control"></select>
</div>

1 个答案:

答案 0 :(得分:1)

您要使用System.DataAnnotations.Display名称而不是描述。按照这个答案: Html.GetEnumSelectList - Getting Enum values with spaces