我有以下代码:
@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>
}
一切正常,但
<h2>@Html.Display(item.Select(x => x.DayName).ToString())</h2>
我只是想在表格上方显示Day Name,因为它按天分组,但显示代码不会显示任何内容。我尝试过使用DisplayFor,但显然它不接受表达式。或许我做错了。
答案 0 :(得分:1)
Html.Display
并非用于此目的,这就是它无法正常工作的原因。你需要的是Html.DisplayFor
。但是,您遇到的错误是因为参数必须是一个表达式,该表达式的计算结果为模型上的成员。使用Select
之类的东西是不可能的,因为无法将表达式解析为特定成员。
现在,鉴于您在此处使用Select
,我们并不完全清楚您希望看到什么样的展示。它将成为一个可枚举的,因此您需要就如何处理该枚举中的每个项目做出一些决定。简单地说,你可以这样做:
<h2>
@foreach (var item in items)
{
@Html.DisplayFor(x => x.DayName)
}
</h2>
但是,由于这是一个标题,因此您可能只期待一天的名称,所以您可能只想做以下事情:
@{ var item = item.First(); }
<h2>@Html.DisplayFor(x => item.DayName)</h2>
然而,在这里甚至不需要DisplayFor
并不完全清楚。如果DayName
只是Monday
之类的字符串,则DisplayFor
完全是多余的;它只会输出字符串。因此,您可以这样做:
<h2>@items.Select(x => x.DayName).First()</h2>