Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...