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

后端 未结 2 999
难免孤独
难免孤独 2020-12-02 15:54

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

相关标签:
2条回答
  • 2020-12-02 16:33

    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; }
    }
    
    0 讨论(0)
  • <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>
    
    0 讨论(0)
提交回复
热议问题