Click here to Skip to main content
Click here to Skip to main content

Grouping Gridview in Asp.Net MVC

, 25 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
A simplified approach to group grid view data in asp.net mvc

Introduction

Grouping data in grid view 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. Developer 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 grid view 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:

Background

This approach uses linq group by to group the data of the grid view 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 beginers should not feel difficulty grasping 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 footer. You may show the same in header too.

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 demonstrate 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 over 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 act as a sample on how to fetch data from Excel and populate the model using generics. To read excel data, a nuget package 'EPPlus' has been used.

Conclusion

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

In my openion, if time permits and performance is your preference, use 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

19 Apr, 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
Technical Lead
India India
Anurag Gandhi currently works in web application design/development and has done so for many years now as he is passionate about programming.
He is extensively involved in Asp.Net and Asp.Net MVC web application architecture, AngularJs, design and development. His languages of choice are C#, Asp.Net, MVC, Asp, C, C++. But he is familiar with many other coding languages. He works with MS Sql Server as the database architecture of choice.
He is active in programming communities and loves to share his knowledge with other developers whenever he gets the opportunity.
He is also a passionate chess player.
 
He can be contacted at: soft.gandhi@gmail.com
Follow on   Twitter   Google+

Comments and Discussions

 
QuestionAdd Paging? PinmemberMember 403936126-Aug-14 9:31 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun21-May-14 20:21 
GeneralRe: My vote of 5 PinprofessionalAnurag Gandhi25-Aug-14 7:58 
QuestionExcellent Article PinmemberMember 332865323-Apr-14 15:00 
AnswerRe: Excellent Article PinprofessionalAnurag Gandhi23-Apr-14 15:41 
GeneralRe: Excellent Article PinmemberMember 332865324-Apr-14 6:46 
GeneralRe: Excellent Article PinprofessionalAnurag Gandhi24-Apr-14 8:38 
GeneralRe: Excellent Article PinmemberMember 332865325-Apr-14 3:38 
QuestionThis looks great. Pinmemberkjmcsd21-Apr-14 9:45 
AnswerRe: This looks great. PinprofessionalAnurag Gandhi21-Apr-14 22:43 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.141015.1 | Last Updated 25 Aug 2014
Article Copyright 2014 by Anurag Gandhi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid