Grouping Gridview in MVC 4

Grouping Gridview in MVC

Introduction

In this post, I explain how to Group data in Gridview using MVC. Sometimes we need to show group data in our MVC Application like show List of State group by Country. Here I have done this using MVC 4. Steps are given below:-

For ASP.Net Developer visit: Grouping Gridview in C#.Net.

Prerequisite

I used followings:
  • .Net framework 4.0
  • Entity Framework
  • SQL Server 2008

Steps :

Just follow the steps and get result easily.

Step - 1 : Create New Project

Go to File > New > Project > Select asp.net mvc4 web application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create two tables and insert data for show grouped data in Gridview

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have created two table 1. CountryMaster 2. StateMaster.
Create the table and insert data for Show in grouped gridview.

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Creare a ModelView

Here in this example, I need a ViewModel for getting data as a single entity.
Add a Folder(ViewModel) into your project root directory. > Right Click on the folder > Add > Class > Enter Class name > Add.
Write the following code to your class.

public class CountryState
{
    public int CountryID { get; set; }
    public string CountryName { get; set; }
    public int StateID { get; set; }
    public string StateName { get; set; }
}

STEP-6: Add Action For Populate Data.

Go To Controller > Add your action > write the following the code and Rebuild your application.
public ActionResult Gridview()
{
    List<CountryState> StateList = new List<CountryState>();
    using (CountryStateEntities dc = new CountryStateEntities())
    {
        var v = (from a in dc.CountryMasters
                    join b in dc.StateMasters on a.CountryID equals b.CountryID
                    select new
                    {
                        a.CountryID,
                        a.CountryName,
                        b.StateID,
                        b.StateName
                    });
        foreach (var i in v)
        {
            StateList.Add(new CountryState
            {
                CountryID = i.CountryID,
                CountryName = i.CountryName,
                StateID = i.StateID,
                StateName = i.StateName
            });
        }
    }
    return View(StateList);
}

Step-7: Add View for show data on a page.

Right Click on your Action > Add View > Enter View name > Check Create a strongly-type view > Select your model class > Select Scaffold templete > Select list > Add.

Modify Your View as follow
@model IEnumerable<MVCGridviewGrouping.ViewModel.CountryState>
@{
    ViewBag.Title = "Gridview";
}
<h2>Gridview Grouping</h2>
<div id="accordion">
    @{
        foreach (var item in Model.Select(a => a.CountryName).Distinct())
        {
            <h3>Country : @item</h3>
            <div>
                 <table cellspacing="10">
                        <tr>                           
                            <th>
                               State ID
                            </th>
                            <th>
                                State Name
                            </th>
                            <th></th>
                        </tr>
                @foreach (var i in Model.Where(a=>a.CountryName.Equals(@item)))
                {
                       <tr>                            
                            <td>
                                @Html.DisplayFor(modelItem => i.StateID)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => i.StateName)
                            </td>
                            <td>
                                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                            </td>
                        </tr>
                }
                </table>
            </div>
        }
    }
</div>
      
<script language="javascript">
    $(function () {
        $("#accordion").accordion({
            heightStyle: "content"
        });
    });
</script>

Step-8: Modify your _Layout.cshtml view

Add some 2 js and 1 CSS file to _Layout.cshtml view

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/javascript" />
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" type="text/javascript"></script>
Remove Line

@Scripts.Render("~/bundles/jquery")

Complete Code Here _Layout.cshtml view 


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>@ViewBag.Title - My ASP.NET MVC Application</title>
        <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
        <meta name="viewport" content="width=device-width" />
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/javascript" />
        <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
        <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js" type="text/javascript"></script>
    </head>
    <body>
        <header>
            <div class="content-wrapper">
                <div class="float-left">
                    <p class="site-title">@Html.ActionLink("your logo here", "Index", "Home")</p>
                </div>
                <div class="float-right">
                    <section id="login">
                        @Html.Partial("_LoginPartial")
                    </section>
                    <nav>
                        <ul id="menu">
                            <li>@Html.ActionLink("Home", "Index", "Home")</li>
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                            <li>@Html.ActionLink("Gridview Grouping","GridView","Home")</li>
                        </ul>
                    </nav>
                </div>
            </div>
        </header>
        <div id="body">
            @RenderSection("featured", required: false)
            <section class="content-wrapper main-content clear-fix">
                @RenderBody()
            </section>
        </div>
        <footer>
            <div class="content-wrapper">
                <div class="float-left">
                    <p>&copy; @DateTime.Now.Year - My ASP.NET MVC Application</p>
                </div>
            </div>
        </footer>      
        @RenderSection("scripts", required: false)
    </body>

</html>

Step-9: Run Application

Look Result show in your browser.

Grouping Gridview in MVC

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.