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

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

    With Core 2.1,

    public static string GetDisplayName(Enum enumValue)
    {
      return enumValue.GetType()?
     .GetMember(enumValue.ToString())?[0]?
     .GetCustomAttribute<DisplayAttribute>()?
     .Name;
    }
    
    0 讨论(0)
  • 2020-11-22 09:57

    Building on Aydin's great answer, here's an extension method that doesn't require any type parameters.

    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
    
    public static class EnumExtensions
    {
        public static string GetDisplayName(this Enum enumValue)
        {
            return enumValue.GetType()
                            .GetMember(enumValue.ToString())
                            .First()
                            .GetCustomAttribute<DisplayAttribute>()
                            .GetName();
        }
    }
    

    NOTE: GetName() should be used instead of the Name property. This ensures that the localized string will be returned if using the ResourceType attribute property.

    Example

    To use it, just reference the enum value in your view.

    @{
        UserPromotion promo = UserPromotion.SendJobOffersByMail;
    }
    
    Promotion: @promo.GetDisplayName()
    

    Output

    Promotion: Send Job Offers By Mail

    0 讨论(0)
提交回复
热议问题