Click here to Skip to main content
13,901,646 members
Click here to Skip to main content
Add your own
alternative version


52 bookmarked
Posted 19 Apr 2014
Licenced CPOL

Grouping Gridview in Asp.Net MVC

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


Grouping data in grid view is becoming an essential part of UI features these days. With 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:


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>
        foreach (var item in group)
                    @Html.DisplayFor(modelItem => item.Name)
                    @Html.DisplayFor(modelItem => item.Designation)
                    @Html.DisplayFor(modelItem => item.Department)
                    @Html.DisplayFor(modelItem => item.Company)
                    @Html.DisplayFor(modelItem => item.Year)
                    @Html.DisplayFor(modelItem => item.Salary)
        <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>

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 () {

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 <code><code>nuget package 'EPPlus' has been used.


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.


19 Apr, 2014: First Version Created.


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


About the Author

Anurag Gandhi
India India
Anurag Gandhi is a Developer, Consultant, Architect, Blogger, Speaker and a Microsoft Employee. He is passionate about programming.
He is extensively involved in Asp.Net Core, MVC/Web API, 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:
He can be contacted at:

Disclaimer: Any posts, article, content present in this website is my personal opinion based on best of my knowledge and experience. None of the content provided by me should be considered as official communication/opinion or my Employer.

You may also be interested in...

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.

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