我如何在ASP.NET MVC视图组数据? [英] How do I group data in an ASP.NET MVC View?
问题描述
在报告工具,如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
报告软件会喜欢这个组是:
The reporting software will group it like this:
Category1
Data1
Data2
Date3
Category2
Data4
Data5
Data6
有没有办法做到这在ASP.NET MVC视图,可能使用一个简单的LINQ短语或LINQ扩展方法在foreach或嵌套的foreach?
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?
推荐答案
如果您的看法是强类型,你可以使用LINQ GROUPBY扩展方法嵌套的foreach:
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屋!