gpt4 book ai didi

c# - asp.net mvc 3 Razor 和 html 表

转载 作者:技术小花猫 更新时间:2023-10-29 11:49:04 26 4
gpt4 key购买 nike

我有 UsersClass,它永远不会超过 10 个元素。我如何在类似这样的 View 中显示带有表的用户类?

我想显示包含 10 个单元格的两行

最佳答案

一如既往,在每个 ASP.NET MVC 应用程序中,我都建议使用适合 View 要求的 View 模型。因此,在此 View 中,您提到了一个表,您希望在其中按每行 5 个元素对这些用户进行分组:

public class MyViewModel
{
public int Key { get; set; }
public IEnumerable<UsersClass> Users { get; set; }
}

然后在 Controller Action 中:

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);
}

最后,强类型 View 非常简单:

@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>

显然,使用显示模板可以进一步简化此 View :

@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>

结果:

enter image description here

关于c# - asp.net mvc 3 Razor 和 html 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499138/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com