Why is my DisplayFor not looping through my IEnumerable<DateTime>?

asp.net-mvc-3, view

Solution

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)

and then inside `~/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>

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.

Problem

I have this line in my view ``` @(Html.DisplayFor(m => m.DaysOfWeek, "_CourseTableDayOfWeek")) ``` where `m.DaysOfWeek` is a `IEnumerable<DateTime>`. 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> ``` And I get the following error: The model item passed into the dictionary is of type '`System.Collections.Generic.List`1[System.DateTime]`', but this dictionary requires a model item of type '`System.DateTime`'. If I refer to the following post: https://stackoverflow.com/a/5652524/277067 The `DisplayFor` should be looping through the IEnumerable and display the template for each item, shouldn't it?

Original source

Related problems