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

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

    I want to contribute with culture-dependent GetDisplayName enum extension. Hope this will be usefull for anyone googling this answer like me previously:

    "standart" way as Aydin Adn and Todd mentioned:

        public static string GetDisplayName(this Enum enumValue)
        {
            return enumValue
                .GetType()
                .GetMember(enumValue.ToString())
                .First()
                .GetCustomAttribute()
                .GetName();
        }
    

    "Culture-dependent" way:

        public static string GetDisplayName(this Enum enumValue, CultureInfo ci)
        {
            var displayAttr = enumValue
                .GetType()
                .GetMember(enumValue.ToString())
                .First()
                .GetCustomAttribute();
    
            var resMan = displayAttr.ResourceType?.GetProperty(@"ResourceManager", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null, null) as ResourceManager;
    
            return resMan?.GetString(displayAttr.Name, ci) ?? displayAttr.GetName();
        }
    

提交回复
热议问题