如何在 ASP.NET MVC 视图中对数据进行分组? [英] How do I group data in an ASP.NET MVC View?

查看:22
本文介绍了如何在 ASP.NET MVC 视图中对数据进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Crystal Reports 等报告工具中,有多种方法可以获取非规范化数据并按数据中的特定列对其进行分组,从而为指定列中的每个唯一项目创建行标题.

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.

如果我有这个:

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

报告软件会这样分组:

Category1
      Data1
      Data2
      Date3
Category2
      Data4
      Data5
      Data6

有没有办法在 ASP.NET MVC 视图中执行此操作,也许使用带有 foreach 或嵌套 foreach 的简单 linq 短语或 linq 扩展方法?

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?

推荐答案

如果你的视图是强类型的,你可以使用嵌套 foreach 的 LINQ GroupBy 扩展方法:

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; }
}

这篇关于如何在 ASP.NET MVC 视图中对数据进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆