2016-03-08 86 views
2

我有如下列举的特性的模型:枚举描述

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

您可以将扩展方法放在任何地方(在您当前的程序集或其他程序集或单独的dll中)。你只是用它作为'​​@ item.Status.DisplayName()'(并且包括必要的'using'语句指向你的程序集。 –

+0

@StephenMuecke我在一个公共静态类'Utils'中添加了DisplayName方法,方法可以在添加'使用ProjectManager.App_Start;'后在我的项目中以'Utils.DisplayName'方式访问,但是它不会在'@ item.Status.DisplayName()'中解析。我现在该做什么? – VSB

+0

你会得到什么错误? –

回答

7

你可以把扩展方法的任何地方。例如在当前项目中,添加一个文件夹(比如)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" />