我正在尝试为枚举Status
创建自定义显示模板,其名称文本是从类成员注释指定的资源加载的。我使用@Html.DisplayFor(...)
实现了简单的显示模板加载。但我不知道如何显示从资源加载的Name
(在ResourcesType
,Display
注释类成员中指定)
代码:
~Views/Shared/DisplayTemplate/Row.cshtml
@using System.ComponentModel.DataAnnotations
@model LeasePlan.Nadmerne_opotrebeni.WebUI.Controllers.Status
@{
var field = Model.GetType().GetField(Model.ToString());
if (field != null)
{
var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault() as DisplayAttribute;
if (display != null)
{
<span class="label status label-info">@((display.Name as string).ToUpper())</span>
}
}
}
Enum Status
public enum Status
{
[Display(Name = "STATUS_LOADING", ResourceType = typeof(Resources.LabelsResources))]
Loading = 1,
[Display(Name = "STATUS_DISABLED", ResourceType = typeof(Resources.LabelsResources))]
Disabled = 2,
}
//编辑:我的解决方案
我找到了解决方案,但我感觉不太好......有没有更好的办法?
~Views/Shared/DisplayTemplate/Row.cshtml
@using System.ComponentModel.DataAnnotations
@model LeasePlan.Nadmerne_opotrebeni.WebUI.Controllers.Status
@{
var field = Model.GetType().GetField(Model.ToString());
if (field != null)
{
dynamic resourcesManager = display.ResourceType.GetProperty("ResourceManager").GetValue(null, null);
var name = resourcesManager.GetString(display.Name as string);
<span class="label status label-info">@(name != null ? name.ToUpper() : name)</span>
}
}