C# 在razor视图中显示枚举描述
我有一个具有枚举属性的模型,如下所示:C# 在razor视图中显示枚举描述,c#,asp.net-mvc,razor,enums,data-annotations,C#,Asp.net Mvc,Razor,Enums,Data Annotations,我有一个具有枚举属性的模型,如下所示: namespace ProjectManager.Models { public class Contract { ..... public enum ContractStatus { [System.ComponentModel.Description("جديد")] New, [System.ComponentMod
namespace ProjectManager.Models
{
public class Contract
{
.....
public enum ContractStatus
{
[System.ComponentModel.Description("جديد")]
New,
[System.ComponentModel.Description("در انتظار پرداخت")]
WaitForPayment,
[System.ComponentModel.Description("پرداخت شده")]
Paid,
[System.ComponentModel.Description("خاتمه يافته")]
Finished
};
public ContractStatus Status { get; set; }
.....
}
}
在我的razor视图中,我想显示每个项目的枚举描述,例如新的。我试图按照中的说明进行操作,但我不知道在何处添加扩展方法以及如何在razor视图文件中调用扩展方法。如果有人能完成我的代码,我将不胜感激:
@model IEnumerable<ProjectManager.Models.Contract>
....
<table class="table">
<tr>
.....
<th>@Html.DisplayNameFor(model => model.Status)</th>
.....
</tr>
@foreach (var item in Model) {
<tr>
......
<td>
@Html.DisplayFor(modelItem => item.Status) //<---what should i write here?
</td>
....
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })|
</td>
</tr>
}
@model IEnumerable
....
.....
@DisplayNameFor(model=>model.Status)
.....
@foreach(模型中的var项目){
......
@Html.DisplayFor(modeleItem=>item.Status)//您可以将扩展方法放在任何位置。例如,在当前项目中,添加文件夹(比如)Extensions
,然后添加静态类
namespace yourProject.Extensions
{
public static class EnumExtensions
{
public static string DisplayName(this Enum value)
{
// the following is my variation on the extension method you linked to
if (value == null)
{
return null;
}
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])field
.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
return value.ToString();
}
}
}
尽管我会考虑创建一个单独的项目并在当前项目中添加对它的引用,这样您就可以在多个项目中使用它(以及其他有用的扩展方法)。
然后在视图中使用yourProject.Extensions;
语句包含一个@并将其用作
<td>@item.Status.DisplayName()</td>
您可以将扩展方法放在任何位置(在当前程序集、另一个程序集或单独的dll中),只需将其用作@item.Status.DisplayName()
(并包括指向您程序集的必要的using
语句。@StephenMuecke我在公共静态类Utils
中添加了DisplayName方法,在使用ProjectManager.App_Start;
添加后,该方法可以作为Utils.DisplayName
在我的项目中访问,但它在中没有解析。)>@item.Status.DisplayName()
。我现在该怎么办?你有什么错误?@StephenMuecke对DisplayName
没有重载方法,然后我注意到我在查看文件开始时和添加后没有使用ProjectManager.App\u Start;
。看来我和MVC有很多关系!你能把你的评论作为回答吗lease:)?我强烈建议您改用它,因为它已经像DescriptionAttribute
一样内置在.Net中,而且它已经有许多您将来可能最需要的属性。
<system.web>
....
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="yourProject.Extensions" />