如何在运行时从Display(Name =)DataAnnotation获取强类型列表支架视图的列标题?

时间:2011-02-09 16:44:15

标签: asp.net-mvc asp.net-mvc-3 razor

如何在List脚手架视图的输出中呈现[Display(Name="Some Title")] DataAnnotations“Some Title”?

我为这个类创建了一个强类型列表支架视图:

public class CompanyHoliday
{
    [Key]
    public int Id { get; set; }

    [Required]
    [Display(Name = "Datum")]
    [DataType(System.ComponentModel.DataAnnotations.DataType.Date)]
    public DateTime Date { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Feiertag Name")]
    public string Name { get; set; }
}

视图如下所示:

@model IEnumerable<Zeiterfassung.Domain.CompanyHoliday>

@{
    ViewBag.Title = "Year";
}

<h2>Year</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
    <th></th>
    <th>
        Date
    </th>
    <th>
        Name
    </th>
</tr>

@foreach (var item in Model) {
<tr>
    <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>
    <td>
        @String.Format("{0:g}", item.Date)
    </td>
    <td>
        @item.Name
    </td>
</tr>
}

</table>

但是,我不希望表头中有“Date”和“Name”。我希望动态渲染“Datum”和“Feiertag Name”。

实际列标题标题应来自Display DataAnnotation。

我该怎么做?

3 个答案:

答案 0 :(得分:18)

有点老话题,但我提出了一种扩展方法来处理这个问题。

让我们说我的模型是:

public class MyModel
{
    [Display(Name = "Some Property")]
    public string SomeProp { get; set; }
}

将此方法放入静态类:

namespace Web.Extensions
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString DisplayNameFor<TModel, TProperty>(this HtmlHelper<IEnumerable<TModel>> helper, Expression<Func<TModel, TProperty>> expression)
        {
            var name = ExpressionHelper.GetExpressionText(expression);
            name = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            var metadata = ModelMetadataProviders.Current.GetMetadataForProperty(() => Activator.CreateInstance<TModel>(), typeof(TModel), name);
            return new MvcHtmlString(metadata.DisplayName);
        }
    } 
}

然后在您的视图中,即IEnumerable<MyModel>,您可以像这样使用它:

@using Web.Extensions
@model IEnumerable<MyModel>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(m => m.AvgElecCost)
        </th>

生成的HTML将是:

        <th>
            Some Property
        </th>

希望它有所帮助!

答案 1 :(得分:14)

这是我遵循的模式。这假设Lists永远不为null,但可以为空,但条件很容易被短路列为空列表。我确实喜欢Brian的扩展方法。

@if (Model.BurgersList.Count > 0)
{
  var meta = Model.BurgersList.First();
   <table>
        <tr>
            <th>
                @Html.DisplayNameFor(m => meta.Title)
            </th>
            <th>
                @Html.DisplayNameFor(m => meta.HasMustard)
            </th>
         //etc....
   @foreach (var item in Model.AssignmentDefinitions)
   {
        <tr>
            <td>
                @Html.DisplayFor(m => item.Title)
            </td>
            <td>
                @Html.DisplayFor(m => item.HasMustard)
            </td>
       //etc...
   }
   </table>
}
else
{ 
    @:No burgers available.  Create(usually make this an action link)  a new one.
}

答案 2 :(得分:4)

//MVC4 has the DisplayNameFor Extensions

public static class HtmlHelperExtensions
{
    public static MvcHtmlString DisplayNameFor<TModel, TProperty>(this HtmlHelper<IEnumerable<TModel>> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return DisplayNameFor(expression);
    }

    public static MvcHtmlString DisplayNameFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return DisplayNameFor(expression);
    }

    private static MvcHtmlString DisplayNameFor<TModel, TProperty>(Expression<Func<TModel, TProperty>> expression)
    {
        var metadata = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, new ViewDataDictionary<TModel>());
        var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string s = metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>());
        return new MvcHtmlString(HttpUtility.HtmlEncode(s));
    }
}