How do I group data in an ASP.NET MVC View?
Asked Answered
K

3

24

In reporting tools like Crystal Reports, there are ways to take denormalized data and group it by a particular column in the data, creating row headings for each unique item in the specified column.

If I have this:

Category1    Data1
Category1    Data2
Category1    Data3
Category2    Data4
Category2    Data5
Category2    Data6

The reporting software will group it like this:

Category1
      Data1
      Data2
      Date3
Category2
      Data4
      Data5
      Data6

Is there a way to do this in an ASP.NET MVC view, perhaps using a simple linq phrase or linq extension method with a foreach or a nested foreach?

Klemm answered 21/7, 2009 at 16:56 Comment(0)
S
54

If your view is strongly typed, you can use the LINQ GroupBy extension method with nested foreach:

<ul>
<% foreach (var group in Model.GroupBy(item => item.Category)) { %>

   <li><%= Html.Encode(group.Key) %>
     <ul>

     <% foreach (var item in group) { %>
       <li><%= Html.Encode(item.Data) %></li>  
     <% } %>

     </ul>
   </li>

<% } %>
</ul>

This will provide output much like your formatted lists in the original question. It assumes your model looks something like:

public class ViewModel
{
    public string Category { get; set; }
    public string Data { get; set; }
}
Supersonics answered 21/7, 2009 at 17:3 Comment(1)
but how will you post it to the controller, actually I am getting null result.Churchlike
V
4
<table class="table table-striped table-bordered">
    @foreach (var plan in Model.GroupBy(p => p.PlanName))
    {
        <thead>
            <tr>
                <th></th>
                <th>
                    @plan.Key
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var plan1 in plan)
            {
                <tr>
                    <td>@plan1.PlanDetails</td>
                    <td>@plan1.PlanOption</td>
                </tr>
            }
        </tbody>
        <tfoot>

        </tfoot>
    }

</table>
Vestment answered 17/4, 2020 at 20:39 Comment(1)
This could benefit from some explanation.Klemm
L
-1

Use the LINQ GroupBy with nested foreach

View model example:

public class ViewModelData
{
    public string Category { get; set; }
    public string Data { get; set; }
}

View

@model IEnumerable<ViewModels.ViewModelData>

<ul>
    @foreach (var group in Model.GroupBy(item => item.Category))
    {
        <li>@group.Key
            <ul>
                @foreach (var item in group)
                {
                    <li>@item.Data</li>
                }
            </ul>
        </li>
    }
</ul>
Lewellen answered 4/10, 2023 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.