How to get the Display Name Attribute of an Enum member via MVC razor code?

后端 未结 20 2826
孤街浪徒
孤街浪徒 2020-11-22 09:30

I\'ve got a property in my model called \"Promotion\" that its type is a flag enum called \"UserPromotion\". Members of my enum have display attributes set as follows:

20条回答
  •  礼貌的吻别
    2020-11-22 09:33

    I'm sorry to do this, but I couldn't use any of the other answers as-is and haven't time to duke it out in the comments.

    Uses C# 6 syntax.

    static class EnumExtensions
    {
        /// returns the localized Name, if a [Display(Name="Localised Name")] attribute is applied to the enum member
        /// returns null if there isnt an attribute
        public static string DisplayNameOrEnumName(this Enum value)
        // => value.DisplayNameOrDefault() ?? value.ToString()
        {
            // More efficient form of ^ based on http://stackoverflow.com/a/17034624/11635
            var enumType = value.GetType();
            var enumMemberName = Enum.GetName(enumType, value);
            return enumType
                .GetEnumMemberAttribute(enumMemberName)
                ?.GetName() // Potentially localized
                ?? enumMemberName; // Or fall back to the enum name
        }
    
        /// returns the localized Name, if a [Display] attribute is applied to the enum member
        /// returns null if there is no attribute
        public static string DisplayNameOrDefault(this Enum value) =>
            value.GetEnumMemberAttribute()?.GetName();
    
        static TAttribute GetEnumMemberAttribute(this Enum value) where TAttribute : Attribute =>
            value.GetType().GetEnumMemberAttribute(value.ToString());
    
        static TAttribute GetEnumMemberAttribute(this Type enumType, string enumMemberName) where TAttribute : Attribute =>
            enumType.GetMember(enumMemberName).Single().GetCustomAttribute();
    }
    

提交回复
热议问题