我有一个枚举属性的模型如下:
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; }
.....
}
}
在我的剃刀视图中,我想显示每个项目的枚举说明,例如جديد
代替New
。我尝试按照this answer中的说明操作,但我不知道在哪里添加扩展方法以及如何在我的剃刀视图文件中调用扩展方法。如果有人能完成我的代码,我将感激不尽:
@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>
}
答案 0 :(得分:8)
您可以将扩展方法放在任何位置。例如,在当前项目中,添加一个文件夹(比如说)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();
}
}
}
虽然我会考虑创建一个单独的项目并在当前项目中添加对它的引用,以便您可以在多个项目中使用它(以及其他有用的扩展方法)。
然后在视图中包含@using yourProject.Extensions;
语句并将其用作
<td>@item.Status.DisplayName()</td>
另请注意,要避免视图中的using
语句,您可以将程序集添加到web.config.cs
文件
<system.web>
....
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="yourProject.Extensions" />