0

My aim is to get the display name attribute from my enumerables so that I can display their values on an index page without having strange formatting and instead clear, readable lines.

My enumerables look like this:

public enum UserStatus
{
        [Display(Name = "Display Name 1")]
        _x = 0,

        [Display(Name = "Display Name 2")]
        _y = 1,

        [Display(Name = "Display Name 3")]
        _z = 2
}

And the HTML looks like:

@Html.DisplayFor(modelItem => item.UserStatus)

I've tried using this suggestion but I ended up getting some strange errors and couldn't manage to get it to work. If anyone knows how to get the attribute from the enum then I'd greatly appreciate the help.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Displaza
  • 75
  • 7

1 Answers1

1

Here is a demo to get display name with enum value:

EnumExtensions:

public static class EnumExtensions
    {
        public static string DisplayName(this Enum value)
        {
            Type enumType = value.GetType();
            var enumValue = Enum.GetName(enumType, value);
            MemberInfo member = enumType.GetMember(enumValue)[0];

            var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
            var outString = ((DisplayAttribute)attrs[0]).Name;

            if (((DisplayAttribute)attrs[0]).ResourceType != null)
            {
                outString = ((DisplayAttribute)attrs[0]).GetName();
            }

            return outString;
        }
       
    }

View:

@EnumExtensions.DisplayName(UserStatus._x)
@EnumExtensions.DisplayName(UserStatus._y)
@EnumExtensions.DisplayName(UserStatus._z)

result:

enter image description here

Update:

View:

@foreach (UserStatus userStatus in (UserStatus[])Enum.GetValues(typeof(UserStatus)))
{
    @EnumExtensions.DisplayName(userStatus)
}

result:

enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • Is there a way to get the enum names in a way I wouldn't have to specify UserStatus.x or UserStatus.y and instead would get those names as the value is passed into it, perhaps a for loop? – Displaza May 24 '21 at 07:39
  • yes sorry your updated answer helped me a lot. Apologies for the late reply its just that I had some errors on my end that caused this to not work as expected but they were wholly my own mistakes, your answer works great. – Displaza Jun 09 '21 at 10:56