我从显示值表(IEnumerable<FooViewModel>
)切换为在Razor页面中显示分组的值表(IEnumerable<IGrouping<DateTime, FooViewModel>>
)。
获取模型属性的显示名称的语法为@Html.DisplayNameFor(model => model.ID)
。
我认为我没有将DisplayNameFor
与IGrouping<DateTime, FooViewModel>
一起使用的正确语法,因为它仅显示模型的属性之一(在这种情况下为ID
):{ {1}}。
正确的语法是什么?
答案 0 :(得分:1)
我认为您的语法正确!
@model IEnumerable<IGrouping<DateTime, FooViewModel>>
@if (Model.Any())
{
/*
* Since we've checked there are groupings, you can just use .First() to get
* the first group.
*
* .Key will give you the key you use to group things by. In this case, it's
* DateTime.
*
* Since there are groupings, there must be elements in the group so it's safe
* to use .ElementAt() to get to the view model, FooViewModel.
*/
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.First().Key)</th>
<th>@Html.DisplayNameFor(model => model.First().ElementAt(0).ID)</th>
</tr>
</thead>
<tbody>
@foreach (var group in Model)
{
<tr>
<td>@group.Key</td>
<td>@String.Join(", ", group.Select(x => x.ID))</td>
</tr>
}
</tbody>
</table>
}
并附有虚假数据:
public class FooViewModel
{
[Display(Name = "Date time")]
public DateTime DateTime { get; set; }
[Display(Name = "Haha ID")]
public int ID { get; set; }
}
var data = new List<FooViewModel>
{
new FooViewModel { DateTime = new DateTime(2019, 06, 25), ID = 1 },
new FooViewModel { DateTime = new DateTime(2019, 06, 25), ID = 2 },
new FooViewModel { DateTime = new DateTime(2019, 06, 24), ID = 3 },
new FooViewModel { DateTime = new DateTime(2019, 06, 23), ID = 4 }
};
它应该像这样: