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

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

    One liner - Fluent syntax

    public static class Extensions
    {
        /// 
        ///     A generic extension method that aids in reflecting 
        ///     and retrieving any attribute that is applied to an `Enum`.
        /// 
        public static TAttribute GetAttribute(this Enum enumValue) 
                where TAttribute : Attribute
        {
            return enumValue.GetType()
                            .GetMember(enumValue.ToString())
                            .First()
                            .GetCustomAttribute();
        }
    }
    

    Example

    public enum Season 
    {
       [Display(Name = "It's autumn")]
       Autumn,
    
       [Display(Name = "It's winter")]
       Winter,
    
       [Display(Name = "It's spring")]
       Spring,
    
       [Display(Name = "It's summer")]
       Summer
    }
    
    public class Foo 
    {
        public Season Season = Season.Summer;
    
        public void DisplayName()
        {
            var seasonDisplayName = Season.GetAttribute();
            Console.WriteLine("Which season is it?");
            Console.WriteLine (seasonDisplayName.Name);
        } 
    }
    

    Output

    Which season is it?
    It's summer

提交回复
热议问题