Monday, 22 June 2015

Grouping Gridview in MVC 4

INTRODUCTION

In this post I am 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 given below:-

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 create two table 1. CountryMaster 2. StateMaster. 
Create 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 get 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 following code to your class. 

  1. public class CountryState
  2. {
  3. public int CountryID{get;set;}
  4. public string CountryName {get;set;}
  5. public int StateID {get;set;}
  6. public string StateName { get; set; }
  7.  
  8. }

STEP-6: ADD ACTION FOR POPULATE DATA.

Go To Controller > Add your action > write following 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 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.

0 comments: