Click here to Skip to main content
14,642,838 members
Articles » Web Development » ASP.NET » General
Article
Posted 19 Apr 2014

Stats

77.3K views
5.4K downloads
53 bookmarked

Grouping Gridview in ASP.NET MVC

Rate this:
4.84 (45 votes)
Please Sign up or sign in to vote.
4.84 (45 votes)
25 Aug 2014CPOL
A simplified approach to group gridview data in ASP.NET MVC

Introduction

Grouping data in gridview is becoming an essential part of UI features these days. With ASP.NET MVC, where you require the complete control over HTML, many people don't like to use 3rd party controls. Developers often use simple for loop to display tabular/grid so that they can customize it according to their needs easily. This article provides you the simplified way to group the gridview data by directly coding in your view. You may also put your customized data in group header and footer according to your need. Additionally, I have also shown the example on how you can use JQuery to implement expand/collapse behavior. I have used the razor view engine but the same approach would work in all other view engines too.

Below is the screen shot of how the grouped gridview would look like:

Image 1

Background

This approach uses Linq group by to group the data of the gridview source and then uses normal conventional loop to display the data in a desired format. JQuery has been used to customize the behavior at client side. For UI look and feel, the default bootstrap is used. In the attached code, the 4 different views have been provided to delve step by step into the final grid so that beginners do not find it difficult to grasp the concept.

Using the Code

Using the code is simple. Just have a look over the View (.cshtml page) where Linq GroupBy query has been used to group the model. Then, we have iterated through the groups and then each data within the group.

The basic code for grouping looks like this:

@foreach(var group in Model.GroupBy(x=>x.Company))
    {
        <tr class="group-header">
            <td colspan="6">
                <span class="h3">@group.Key</span>
            </td>
        </tr>
        foreach (var item in group)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Designation)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Department)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Company)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Year)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Salary)
                </td>
            </tr>
        }
        <tr class="group-footer">
            <td colspan="6">
                <span class="label label-info">Company: @group.Key</span>
                <span class="label label-success">Total Employee: @group.Count()</span>
                <span class="label label-primary">Avg Salary: 
                       @group.Average(x => x.Salary).ToString("C")</span>
            </td>
        </tr>
    }  

In the above code, first, we are creating a group based on the field which is required to be grouped. Then, looping through each group which has code to generate group header and footer as a table row. Then, we have implemented a nested foreach loop to loop through each item in the group and display the data. In group header and footer, you can implement any custom logic and display the data in any format. In this case, we have demonstrated a basic linq operation like total count and Average in the footer. You may show the same in the header too.

Image 2

Styling and Scripting

The above code will show the grouped data in your browser but to add Expand/Collapse feature, a little bit of JQuery is needed.

The code for expand/collapse looks like this:

$(function () {
        $('.group-header').click(function () {
            $(this).nextUntil('.group-header').toggle();
        });
    }); 

In this code, we are simply handling click event of each group header. Since, a class 'group-header' was assigned to each table header row of the grid, we can use this selector to toggle the display of that group.

In addition to the above, you may also implement various other styling or scripting behavior like:

  • Expanding/Collapsing all headers
  • Toggling all headers/footers
  • Expanding/Collapsing all data, etc.

Adding Index to Row

Index to each row in a grid can be added just by 2-3 lines of JQuery code. The code below demonstrates this:

function addPaging() {
        $('#employeeGrid tr:first').prepend('<th style="width:60px;">S. No.</th>');
        $('#employeeGrid tr:not(:first, .group-header, .group-footer)').each(function (index) {
            $(this).prepend('<td class="text-right">' + (index + 1) + '.</td>');
        });
    }

The first line of the function adds a th (table header column) tag to the first row of the grid table. The next code loops through each row of the HTML table and prepends a new td tag to each row (tr tag) with index applied to it. Please have a look at the Sample Grid page of the attached code to see things in action.

Points of Interest

Apart from grouping gridview data in MVC, the code also acts as a sample on how to fetch data from Excel and populate the model using generics. To read Excel data, a <code><code>nuget package 'EPPlus' has been used.

Conclusion

Since you are using the raw HTML to generate your grid, the sky is your limit. You can customize your grid to whatever extent you want. You may not get a high degree of flexibility if you are using any 3rd party control.

In my opinion, if time permits and performance is your preference, use the native approach. Else, there are a lot of MVC Grid tools (paid as well as free) in the market which will help you to develop your application quickly.

History

  • 19th April, 2014: First version created

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Anurag Gandhi
Architect
India India
Anurag Gandhi is a Freelance Developer and Consultant, Architect, Blogger, Speaker, and Ex Microsoft Employee. He is passionate about programming.
He is extensively involved in Asp.Net Core, MVC/Web API, Node/Express, Microsoft Azure/Cloud, web application hosting/architecture, Angular, AngularJs, design, and development. His languages of choice are C#, Node/Express, JavaScript, Asp .NET MVC, Asp, C, C++. He is familiar with many other programming languages as well. He mostly works with MS SQL Server as the preferred database and has worked with Redis, MySQL, Oracle, MS Access, etc. also.
He is active in programming communities and loves to share the knowledge with others whenever he gets the time for it.
He is also a passionate chess player.
Linked in Profile: https://in.linkedin.com/in/anuraggandhi
He can be contacted at soft.gandhi@gmail.com

Comments and Discussions

 
Questiongood article Pin
Member 126609771-Sep-17 8:18
MemberMember 126609771-Sep-17 8:18 
QuestionBest way to do a simple Grouping in Mvc by using Linq Pin
k.nisha Cuty9-Jul-15 2:25
Memberk.nisha Cuty9-Jul-15 2:25 
QuestionThank you very much Pin
Member 1158100328-May-15 13:19
MemberMember 1158100328-May-15 13:19 
AnswerRe: Thank you very much Pin
Anurag Gandhi9-Dec-15 3:40
professionalAnurag Gandhi9-Dec-15 3:40 
QuestionAdd Paging? Pin
Member 403936126-Aug-14 9:31
MemberMember 403936126-Aug-14 9:31 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun21-May-14 20:21
MemberHumayun Kabir Mamun21-May-14 20:21 
GeneralRe: My vote of 5 Pin
Anurag Gandhi25-Aug-14 7:58
professionalAnurag Gandhi25-Aug-14 7:58 
QuestionExcellent Article Pin
Kevin Gaskin23-Apr-14 15:00
MemberKevin Gaskin23-Apr-14 15:00 
AnswerRe: Excellent Article Pin
Anurag Gandhi23-Apr-14 15:41
professionalAnurag Gandhi23-Apr-14 15:41 
GeneralRe: Excellent Article Pin
Kevin Gaskin24-Apr-14 6:46
MemberKevin Gaskin24-Apr-14 6:46 
GeneralRe: Excellent Article Pin
Anurag Gandhi24-Apr-14 8:38
professionalAnurag Gandhi24-Apr-14 8:38 
GeneralRe: Excellent Article Pin
Kevin Gaskin25-Apr-14 3:38
MemberKevin Gaskin25-Apr-14 3:38 
QuestionThis looks great. Pin
kjmcsd21-Apr-14 9:45
Memberkjmcsd21-Apr-14 9:45 
AnswerRe: This looks great. Pin
Anurag Gandhi21-Apr-14 22:43
professionalAnurag Gandhi21-Apr-14 22:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.