在剃刀视图中显示枚举描述

VSB*_*VSB 2 c# asp.net-mvc enums data-annotations razor

我有一个枚举属性的模型如下:

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

}
Run Code Online (Sandbox Code Playgroud)

在我的剃刀视图中,我想显示每个项目的枚举描述,例如,????而不是New.我试着按照这个答案中的说明,但我不知道在哪里添加扩展方法以及如何在我的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>
}
Run Code Online (Sandbox Code Playgroud)

小智 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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然我会考虑创建一个单独的项目,并在当前项目中添加对它的引用,以便您可以在多个项目中使用它(以及其他有用的扩展方法).

然后@using yourProject.Extensions;在视图中包含一个语句并将其用作

<td>@item.Status.DisplayName()</td>
Run Code Online (Sandbox Code Playgroud)

另请注意,要避免using视图中的语句,可以将程序集添加到web.config.cs文件中

<system.web>
    ....
    <pages>
        <namespaces>
            <add namespace="System.Web.Helpers" />
            <add namespace="yourProject.Extensions" />
Run Code Online (Sandbox Code Playgroud)