Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make MVC3 DisplayFor show the value of an Enum's Display-Attribute?

in a MVC3-Project, I'm using an enum with display-Attributes:

public enum Foo {
  [Display(Name = "Undefined")]
  Undef = 0,

  [Display(Name = "Fully colored")]
  Full = 1
}

The model class has a property using this enum:

public Foo FooProp { get; set; }

The view uses the model class and displays the property via

@Html.DisplayFor(m => m.FooProp)

Now, finally, my question:

How can I make .DisplayFor() show the string from the Display-Attribute instead of showing only the enum's value-name? (it should show "Undefined" or "Fully colored", but displaysp "Undef" or "Full").

Thanks for tips!

like image 345
Sascha Avatar asked Jun 05 '11 18:06

Sascha


1 Answers

A custom display template might help (~/Views/Shared/DisplayTemplates/Foo.cshtml):

@using System.ComponentModel.DataAnnotations
@model Foo

@{
    var field = Model.GetType().GetField(Model.ToString());
    if (field != null)
    {
        var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
        if (display != null)
        {
            @display.Name
        }
    }
}
like image 61
Darin Dimitrov Avatar answered Nov 06 '22 01:11

Darin Dimitrov