开发者

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-At开发者_高级运维tribute 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
        }
    }
}


Another Solution

NOTE: This code does not rely on @Html.DisplayFor()

I did it like this...

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

namespace Nilhoor.Utility.Extensions
{
    public static class EnumExtensions
    {
        .
        .
        .

        public static string GetDisplayName(this Enum @enum)
        {
            var memberName = @enum.ToString();
            
            var nameAttribute = @enum.GetType().GetMember(memberName).FirstOrDefault()?.GetCustomAttribute<DisplayAttribute>();
            
            return nameAttribute != null 
                ? nameAttribute.GetName() 
                : memberName;
        }
    }
}

In x.cshtml

@using Nilhoor.Utility.Extensions
.
.
.
<span>Value: </span>
<span>@Model.Type.GetDisplayName()</span>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜