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

后端 未结 20 2845
孤街浪徒
孤街浪徒 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:35

    combining all edge-cases together from above:

    • enum members with base object members' names (Equals, ToString)
    • optional Display attribute

    here is my code:

    public enum Enum
    {
        [Display(Name = "What a weird name!")]
        ToString,
    
        Equals
    }
    
    public static class EnumHelpers
    {
        public static string GetDisplayName(this Enum enumValue)
        {
            var enumType = enumValue.GetType();
    
            return enumType
                    .GetMember(enumValue.ToString())
                    .Where(x => x.MemberType == MemberTypes.Field && ((FieldInfo)x).FieldType == enumType)
                    .First()
                    .GetCustomAttribute()?.Name ?? enumValue.ToString();
        }
    }
    
    void Main()
    {
        Assert.Equals("What a weird name!", Enum.ToString.GetDisplayName());
        Assert.Equals("Equals", Enum.Equals.GetDisplayName());
    }
    

提交回复
热议问题