Select HTML 助手获取扩展方法不是枚举字符串

Select HTML helper get extension method not enum string

我创建了一个枚举扩展:

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>

效果很好!

所以我希望在 select 下拉列表中使用此描述。 但似乎无法在 Razor 视图中找到一种方法,使用 HTML.Helpers。我应该把调用 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>

您想使用 System.DataAnnotations.Display 名称而不是描述。根据这个答案: