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

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

    Building further on Aydin's and Todd's answers, here is an extension method that also lets you get the name from a resource file

    using AppResources;
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Reflection;
    using System.Resources;
    
    public static class EnumExtensions
    {
        public static string GetDisplayName(this Enum enumValue)
        {
            var enumMember= enumValue.GetType()
                            .GetMember(enumValue.ToString());
    
            DisplayAttribute displayAttrib = null;
            if (enumMember.Any()) {
                displayAttrib = enumMember 
                            .First()
                            .GetCustomAttribute();
            }
    
            string name = null;
            Type resource = null;
    
            if (displayAttrib != null)
            {
                name = displayAttrib.Name;
                resource = displayAttrib.ResourceType;
            }
    
            return String.IsNullOrEmpty(name) ? enumValue.ToString()
                : resource == null ?  name
                : new ResourceManager(resource).GetString(name);
        }
    }
    

    and use it like

    public enum Season 
    {
        [Display(ResourceType = typeof(Resource), Name = Season_Summer")]
        Summer
    }
    

提交回复
热议问题