本文介绍了为什么我的 DisplayFor 没有遍历我的 IEnumerable<DateTime>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为有这条线

@(Html.DisplayFor(m => m.DaysOfWeek, "_CourseTableDayOfWeek"))

其中 m.DaysOfWeekIEnumerable.

有_CourseTableDayOfWeek.cshtml的内容:

There is the content of _CourseTableDayOfWeek.cshtml:

@model DateTime
@{
    ViewBag.Title = "CourseTableDayOfWeek";
}
<th>
    @System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int) Model.DayOfWeek]
    <span class="dateString">Model.ToString("G")</span>
</th>

我收到以下错误:

传入字典的模型项的类型为System.Collections.Generic.List`1[System.DateTime]",但此字典需要类型为"的模型项System.DateTime'.

如果我参考以下帖子:

https://stackoverflow.com/a/5652524/277067

DisplayFor 应该循环遍历 IEnumerable 并显示每个项目的模板,不是吗?

The DisplayFor should be looping through the IEnumerable and display the template for each item, shouldn't it?

推荐答案

它不会循环,因为您已将显示模板的名称指定为 DisplayFor 帮助程序 (_CourseTableDayOfWeek).

It's not looping because you have specified a name for the display template as second argument of the DisplayFor helper (_CourseTableDayOfWeek).

仅当您依赖约定时才会循环,即

It loops only when you rely on conventions i.e.

@Html.DisplayFor(m => m.DaysOfWeek)

然后在~/Views/Shared/DisplayTemplates/DateTime.cshtml中:

@model DateTime
@{
    ViewBag.Title = "CourseTableDayOfWeek";
}
<th>
    @System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.DayNames[(int) Model.DayOfWeek]
    <span class="dateString">Model.ToString("G")</span>
</th>

一旦您为显示模板指定了自定义名称(作为 DisplayFor 助手的第二个参数或作为 [UIHint] 属性),它将不再循环获取集合属性,模板将只是通过 IEnumerable 作为模型.

Once you specify a custom name for the display template (either as second argument of the DisplayFor helper or as [UIHint] attribute) it will no longer loop for collection properties and the template will simply be passed the IEnumerable<T> as model.

这很令人困惑,但就是这样.我也不喜欢.

It's confusing but that's how it is. I don't like it either.

这篇关于为什么我的 DisplayFor 没有遍历我的 IEnumerable<DateTime>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:32