Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 277
remi bourgarel Avatar asked Dec 30 '11 11:12

remi bourgarel


1 Answers

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.

like image 131
Darin Dimitrov Avatar answered Sep 18 '22 20:09

Darin Dimitrov