Asp.net-Mvc-3

如何使 MVC3 DisplayFor 顯示列舉的顯示屬性的值?

  • October 10, 2021

在 MVC3 項目中,我使用的是帶有顯示屬性的列舉:

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

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

模型類具有使用此列舉的屬性:

public Foo FooProp { get; set; }

視圖使用模型類並通過顯示屬性

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

現在,最後,我的問題:

如何使 .DisplayFor() 顯示來自 Display-Attribute 的字元串,而不是僅顯示列舉的值名稱?(它應該顯示“未定義”或“全彩色”,但顯示“未定義”或“全彩色”)。

感謝您的提示!

自定義顯示模板可能會有所幫助(~/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
       }
   }
}

另一種解決方案

注意:此程式碼不依賴@Html.DisplayFor()

我是這樣做的…

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

在 x.cshtml 中

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

引用自:https://stackoverflow.com/questions/6245074