3

I have an enum with Display(Name=) that I wish to display in a Razor view but I'm getting only the value.

 public enum Gender
 {
    [Display(Name = "Man woman")]
    EveryOne = 0,
    [Display(Name = "Man")]
    Man = 1,
    [Display(Name = "Woman")]
    Woman = 2
 }

Razor:

 Is for: @Model.LectureGig.Gender

The Html results are:

Is for: Everyone

Instead of:

Is for: Man woman

Peter B
  • 22,460
  • 5
  • 32
  • 69
Assaf Our
  • 611
  • 3
  • 9
  • 25
  • 3
    You have to get the attribute value yourself - see http://stackoverflow.com/questions/13099834/how-to-get-the-display-name-attribute-of-an-enum-member-via-mvc-razor-code – stuartd Nov 30 '16 at 12:59

1 Answers1

8

like this:

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

& the view :

@Model.LectureGig.Gender.GetDisplayName()
Assaf Our
  • 611
  • 3
  • 9
  • 25