Looping through models content in Razor

前端 未结 3 545
既然无缘
既然无缘 2021-02-05 16:39

I want to loop through each item in my model in my razor view but I want to group all items together. I then want to loop through each group. Imagine I have a table:

<         


        
相关标签:
3条回答
  • 2021-02-05 17:03

    Yes, this is easy to do using the Linq GroupBy. I'd suggest changing your view to use @model IEnumerable<IGrouping<string, MyModel>>, which you'd populate like this:

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

    Then, simply iterate through the group as you wrote, except using group.Key instead of group.GroupNo to retrieve IGrouping's key:

    @foreach (var group in Model) {
        <section>
            <header>Group No is @group.Key</header>
            @foreach (var item in group) {
                <p>GroupName: @item.GroupName</p>
            }
        </section>
    } 
    
    0 讨论(0)
  • 2021-02-05 17:13

    LINQ can help you do that

    @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>
    }
    
    0 讨论(0)
  • 2021-02-05 17:16
    @{
        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
    
    0 讨论(0)
提交回复
热议问题