加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何从运行时的强类型列表框架视图的Display(Nam

发布时间:2020-12-16 00:34:49 所属栏目:asp.Net 来源:网络整理
导读:如何在列表脚手架视图的输出中显示[Display(Name =“Some Title”)] DataAnnotations“Some Title” 我为这个类创建了一个强类型的列表脚本视图: public class CompanyHoliday{ [Key] public int Id { get; set; } [Required] [Display(Name = "Datum")] [D
如何在列表脚手架视图的输出中显示[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>

但是,我不想在表头中使用“日期”和“名称”。我想要动态地呈现“基准”和“飞标名”。

实际列标题应来自Display DataAnnotation。

我该如何做?

解决方法

一个旧主题的位,但我想出了一个扩展方法来处理这个。

让我说我的模型是:

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

然后在您的View中,它正在使用IEnumerable< MyModel>,您可以使用它:

@using Web.Extensions
@model IEnumerable<MyModel>

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

生成的HTML将是:

<th>
            Some Property
        </th>

希望有帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读