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

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

    Building on Todd's great answer which built on Aydin's great answer, here's a generic extension method that doesn't require any type parameters.

    /// 
    /// Gets human-readable version of enum.
    /// 
    /// DisplayAttribute.Name property of given enum.
    public static string GetDisplayName(this T enumValue) where T : IComparable, IFormattable, IConvertible
    {
        if (!typeof(T).IsEnum)
            throw new ArgumentException("Argument must be of type Enum");
    
        DisplayAttribute displayAttribute = enumValue.GetType()
                                                     .GetMember(enumValue.ToString())
                                                     .First()
                                                     .GetCustomAttribute();
    
        string displayName = displayAttribute?.GetName();
    
        return displayName ?? enumValue.ToString();
    }
    

    I needed this for my project because something like the below code, where not every member of the enum has a DisplayAttribute, does not work with Todd's solution:

    public class MyClass
    {
        public enum MyEnum 
        {
            [Display(Name="ONE")]
            One,
            // No DisplayAttribute
            Two
        }
        public void UseMyEnum()
        {
            MyEnum foo = MyEnum.One;
            MyEnum bar = MyEnum.Two;
            Console.WriteLine(foo.GetDisplayName());
            Console.WriteLine(bar.GetDisplayName());
        }
    }
    // Output:
    //
    // ONE
    // Two
    

    If this is a complicated solution to a simple problem, please let me know, but this was the fix I used.

提交回复
热议问题