我有 UsersClass,它永远不会有超过 10 个项目。如何在这样的视图中显示带有表格的用户类?
我想显示两行 10 个单元格
与往常一样,在每个 ASP.NET MVC 应用程序中,我建议使用适合视图要求的视图模型。因此,在此视图中,您提到了一个表,您希望在该表中按每行 5 个元素对这些用户进行分组:
public class MyViewModel
{
public int Key { get; set; }
public IEnumerable<UsersClass> Users { get; set; }
}
然后在控制器动作中:
public ActionResult Index()
{
// that's your domain model => a list of UsersClass
// could be coming from wherever you want
var users = Enumerable.Range(1, 7).Select(x => new UsersClass
{
Id = x
});
// Now let's group those users into the view model:
// We will have 5 elements per row
var model = users
.Select((u, index) => new { User = u, Index = index })
.GroupBy(x => x.Index / 5)
.Select(x => new MyViewModel
{
Key = x.Key,
Users = x.Select(y => y.User)
});
return View(model);
}
最后,强类型视图非常简单:
@model IEnumerable<MyViewModel>
<table>
@foreach (var item in Model)
{
<tr>
@foreach (var user in item.Users)
{
<td>@user.Id</td>
}
<!-- That's just to fill the row with the remaining
td if we have less than 5 users. Obviously
depending on your requirements you could use
a single td with a calculated colspan or something else
-->
@for (int i = item.Users.Count(); i < 5; i++)
{
<td></td>
}
</tr>
}
</table>
显然,可以使用显示模板进一步简化此视图:
@model IEnumerable<MyViewModel>
<table>
@Html.DisplayForModel()
</table>
并在相应的显示模板中:
@model MyViewModel
<tr>
@Html.DisplayFor(x => x.Users)
@for (int i = item.Users.Count(); i < 5; i++)
{
<td></td>
}
</tr>
和 UsersClass 显示模板:
@model UsersClass
<td>@user.Id</td>
结果:
不确定这是否正是您要查找的内容,但如果不准确,您应该可以轻松修改它:
@* Check to make sure your user class is not null *@
@if (Model.UserClass != null)
{
<table>
for (int i = 1; i <= 2; i++)
{
<tr>
for (int j = 1; j <= 5; j++)
{
<td>if (Model.UserClass[(j*i)-1] != null) { Model.UserClass[(j*i)-1] }</td>
}
</tr>
}
</table>
}
我写得很快,但这应该接近你所需要的。