How to make MVC3 DisplayFor show the value of an E

2020-02-25 08:18发布

问题:

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!

回答1:

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
        }
    }
}