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!
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With