Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 635
Robert Harvey Avatar asked Jul 21 '09 16:07

Robert Harvey


2 Answers

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; }
}
like image 102
Jason Avatar answered Oct 20 '22 00:10

Jason


<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>
like image 3
Rahul Bhalekar Avatar answered Oct 20 '22 00:10

Rahul Bhalekar