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

后端 未结 20 2705
孤街浪徒
孤街浪徒 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: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()
                            .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

提交回复
热议问题