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

后端 未结 20 2724
孤街浪徒
孤街浪徒 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条回答
  •  Happy的楠姐
    2020-11-22 09:31

    Based on previous answers I've created this comfortable helper to support all DisplayAttribute properties in a readable way:

    public static class EnumExtensions
        {
            public static DisplayAttributeValues GetDisplayAttributeValues(this Enum enumValue)
            {
                var displayAttribute = enumValue.GetType().GetMember(enumValue.ToString()).First().GetCustomAttribute();
    
                return new DisplayAttributeValues(enumValue, displayAttribute);
            }
    
            public sealed class DisplayAttributeValues
            {
                private readonly Enum enumValue;
                private readonly DisplayAttribute displayAttribute;
    
                public DisplayAttributeValues(Enum enumValue, DisplayAttribute displayAttribute)
                {
                    this.enumValue = enumValue;
                    this.displayAttribute = displayAttribute;
                }
    
                public bool? AutoGenerateField => this.displayAttribute?.GetAutoGenerateField();
                public bool? AutoGenerateFilter => this.displayAttribute?.GetAutoGenerateFilter();
                public int? Order => this.displayAttribute?.GetOrder();
                public string Description => this.displayAttribute != null ? this.displayAttribute.GetDescription() : string.Empty;
                public string GroupName => this.displayAttribute != null ? this.displayAttribute.GetGroupName() : string.Empty;
                public string Name => this.displayAttribute != null ? this.displayAttribute.GetName() : this.enumValue.ToString();
                public string Prompt => this.displayAttribute != null ? this.displayAttribute.GetPrompt() : string.Empty;
                public string ShortName => this.displayAttribute != null ? this.displayAttribute.GetShortName() : this.enumValue.ToString();
            }
        }
    

提交回复
热议问题