通过在剃刀模式内容循环(Looping through models content in Razo

2019-08-01 23:35发布

我想通过我在我的Razor视图模型中的每个项循环,但我希望将所有物品放在一起。 然后我想通过每组回路。 想象一下,我有一个表:

ID   GroupNo    GroupName
1    1          Group1
2    1          Group2
3    1          Group3
4    2          Group1
5    2          Group2
6    3          Group56

我想要做的事,如:

@foreach (var group in Model.GroupNo) {
    <section>
        <header>Group No is @group.GroupNo</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
} 

所以我的输出是:

Group No is 1
GroupName: Group1
GroupName: Group2
GroupName: Group3
Group No is 2
GroupName: Group1
GroupName: Group2
Group No is 3
GroupName: Group56

这可能吗?

谢谢

Answer 1:

是的,这是很容易使用LINQ到做GroupBy 。 我建议改变你的视图中使用@model IEnumerable<IGrouping<string, MyModel>> ,你会填充像这样:

var groupModel = MyModelCollection.GroupBy(item => item.GroupNo).ToArray();
return View(groupModel);

然后,只需通过迭代组为你写的,但是使用了group.Key代替group.GroupNo检索IGrouping的关键:

@foreach (var group in Model) {
    <section>
        <header>Group No is @group.Key</header>
        @foreach (var item in group) {
            <p>GroupName: @item.GroupName</p>
        }
    </section>
} 


Answer 2:

LINQ可以帮助你做到这一点

@model IEnumerable<Project1.Models.Group>


@foreach (var item in Model.Select(i=>i.groupno).Distinct().ToList()) {
    <tr>
        <td>
            <header>Group No is @item</header>
            @foreach (var grpName in Model.Where(i => i.groupno == item).ToList())
            {
                <p>GroupName: @grpName.groupName</p>
            }
        </td>
    </tr>
}


Answer 3:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>

        @{
            String[] name = {"Prashant", "Rishabh", "Zaheer", "Pratima", "Rahul"};
            int i = 1;
            while (i <= 5)
            {
                foreach(var x in name)
                {
                       <p>@i.  @x</p>
                       i++;
                };
                break;
            }
        }
    </div>
</body>
</html>

O/p-
1. Prashant

2. Rishabh

3. Zaheer

4. Pratima

5. Rahul


文章来源: Looping through models content in Razor