如何从显示器(名称=)DataAnnotation在运行时一个强类型的列表视图脚手架拿到列标题? [英] How to get the column titles from the Display(Name=) DataAnnotation for a strongly typed list scaffold view at runtime?
问题描述
我如何获得 [显示(名称=一些标题)]
DataAnnotations有些题目,在列表脚手架视图的输出呈现?
How do I get the [Display(Name="Some Title")]
DataAnnotations "Some Title" rendered in the List scaffold view's output?
我创建这个类的强类型列表脚手架视图:
I create a strongly typed list scaffold view for this class:
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; }
}
的观点是这样的:
The view looks like this:
@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>
不过,我不希望在表头日期和姓名。我想原点和Feiertag名动态呈现在那里。
However, I don't want "Date" and "Name" in the table header. I want "Datum" and "Feiertag Name" rendered there dynamically.
实际的列标题标题应该来自显示DataAnnotation。
The actual column header titles should come from the Display DataAnnotation.
我如何做到这一点?
推荐答案
一个老话题的位,但我想出了一个扩展方法来处理这个问题。
Bit of an old topic, but I came up with an extension method to handle this.
让说我的模式是:
public class MyModel
{
[Display(Name = "Some Property")]
public string SomeProp { get; set; }
}
放弃这一方法成为一个静态类:
Drop this method into a static class:
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&LT;&为MyModel GT;
,您可以使用它是这样的:
Then in your View, which is taking an IEnumerable<MyModel>
, you can use it like this:
@using Web.Extensions
@model IEnumerable<MyModel>
<table>
<tr>
<th>
@Html.DisplayNameFor(m => m.AvgElecCost)
</th>
生成的HTML将是:
The generated HTML will be:
<th>
Some Property
</th>
希望它帮助!
这篇关于如何从显示器(名称=)DataAnnotation在运行时一个强类型的列表视图脚手架拿到列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!