Reputation: 73
I have the following code:
@model IEnumerable<SampleMvcApp.Models.Exercise>
@foreach (var item in Model.GroupBy(m => m.DayName).Distinct())
{
<table class="table">
<h2>@Html.Display(item.Select(x => x.DayName).ToString())</h2>
<thead>
<tr>
<th>
ExerciseName
</th>
<th>
ExerciseTime
</th>
<th>
ExerciseRepetition
</th>
<th>
MomentOfTheDay
</th>
<th>
Routine
</th>
<th>
Week
</th>
</tr>
</thead>
@foreach (var test2 in item)
{
<tbody>
<tr>
<td>
@Html.DisplayFor(modelItem => test2.ExerciseName)
</td>
<td>
@Html.DisplayFor(modelItem => test2.ExerciseTime)
</td>
<td>
@Html.DisplayFor(modelItem => test2.ExerciseRepetition)
</td>
<td>
@Html.DisplayFor(modelItem => test2.MomentOfTheDay)
</td>
<td>
@Html.DisplayFor(modelItem => test2.Routine.RoutineID)
</td>
<td>
@Html.DisplayFor(modelItem => test2.ExerciseWeek)
</td>
<td>
<a asp-action="Edit" asp-route-id="@test2.ExerciseID">Edit</a> |
<a asp-action="Details" asp-route-id="@test2.ExerciseID">Details</a> |
<a asp-action="Delete" asp-route-id="@test2.ExerciseID">Delete</a>
</td>
</tr>
</tbody>
}
</table>
}
Everything works fine but
<h2>@Html.Display(item.Select(x => x.DayName).ToString())</h2>
I'm just trying to show the Day Name above the table as it is grouped by days, however the Display code won't show anything. I've tried using DisplayFor but apparently it doesn't accept expressions. Or maybe I am doing it wrong.
Upvotes: 0
Views: 515
Reputation: 239290
Html.Display
is not intended for this purpose, which is why it doesn't work. What you need is Html.DisplayFor
. However, the error you're getting with that is because the parameter must be an expression that evaluates to an member on the model. Using something like Select
is not possible because the expression cannot be parsed to a particular member.
Now, given your use of Select
here, it's not entirely clear what kind of display you're expecting to see. It's going to be an enumerable, so you'd need to make some decision about how each item in that enumerable should be handled. Simply, you could do something like:
<h2>
@foreach (var item in items)
{
@Html.DisplayFor(x => x.DayName)
}
</h2>
However, since this is a heading, it's likely you're only expecting a single day name, so you might rather just do something like:
@{ var item = item.First(); }
<h2>@Html.DisplayFor(x => item.DayName)</h2>
Yet, it's not entirely clear if DisplayFor
is even necessary here. If DayName
is just a string like Monday
, then DisplayFor
is entirely superfluous; it will merely just output the string. Therefore, you could just do:
<h2>@items.Select(x => x.DayName).First()</h2>
Upvotes: 1