Tuesday, 2 December 2014

MVC 4 Razor: Create Nested WebGrid with Expand/Collapse in ASP.NET MVC4.

Hi friends,in this article I will explain about How to create Nested WebGrid with Expand/Collapse in ASP.NET MVC 4 Razor.

I already explained in the previous articles about MVC 4 Razor: Inline Editing in WebGrid || WebGrid with inline editing, updating, cancel and delete the record using JSON AJAX , MVC4 Razor: How to bind the Checkboxlist from the database || How to create a CheckboxList in MVC4 Razor and MVC 4 Razor: How to Select / Deselect All Checkboxes inside a Webgrid in ASP.NET Application using C#.NET.

Lets explain How to Create Nested WebGrid with Expand/Collapse in ASP.NET MVC4 Razor.
DBScript:
CREATE TABLE Department_Details (
  Dept_id int IDENTITY (1, 1) PRIMARY KEY,
  Dept_Name varchar(50)
)

INSERT INTO Department_Details (Dept_Name)
  VALUES ('Technical')
INSERT INTO Department_Details (Dept_Name)
  VALUES ('Administration')
INSERT INTO Department_Details (Dept_Name)
  VALUES ('Accounts')
INSERT INTO Department_Details (Dept_Name)
  VALUES ('HR')


CREATE TABLE Employee_Details (
  Emp_id int IDENTITY (1, 1) PRIMARY KEY,
  Emp_Name varchar(50),
  Address varchar(200),
  Dept_id int FOREIGN KEY (Dept_id) REFERENCES Department_Details (Dept_id)
)

INSERT INTO Employee_Details (Emp_Name, Address, Dept_id)
  VALUES ('Kishore', 'XXXXXXXX', 1)
INSERT INTO Employee_Details (Emp_Name, Address, Dept_id)
  VALUES ('SaiR', 'XXXXXXXX', 1)
INSERT INTO Employee_Details (Emp_Name, Address, Dept_id)
  VALUES ('SambhaShiva', 'XXXXXXXX', 2)
INSERT INTO Employee_Details (Emp_Name, Address, Dept_id)
  VALUES ('Satyam', 'XXXXXXXX', 3)
INSERT INTO Employee_Details (Emp_Name, Address, Dept_id)
  VALUES ('Raghav', 'XXXXXXXX', 4)

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. 


Add Department_Details and Employee_Details tables in the ADO.NET Entity Data Model then connectionstring will be added in the web.config file and Emp_Dept.edmx will be created when you give the ADO.NET Entity Data Model as Emp_Dept.edmx .







Model(Emp_Dept.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcNestedWebgrid.Models
{
    public class Emp_Dept
    {
        public Department_Details dept { get; set; }
        public List<Employee_Details> Emp_Details { get; set; }
    }
}

Controller(EmpDeptController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcNestedWebgrid.Models;

namespace MvcNestedWebgrid.Controllers
{
    public class EmpDeptController : Controller
    {
        public ActionResult Index()
        {
            List<Emp_Dept> objDetails = new List<Emp_Dept>();

            using (DBEntities db = new DBEntities())
            {
                var o = db.Department_Details.OrderByDescending(a => a.Dept_id);
                foreach (var i in o)
                {
                    var od = db.Employee_Details.Where(x => x.Dept_id == i.Dept_id).ToList();
                    objDetails.Add(new Emp_Dept { dept = i, Emp_Details = od });
                }
            }
            return View(objDetails);
        }
    }
}

View(Index.cshtml):
@model IEnumerable<MvcNestedWebgrid.Models.Emp_Dept>
@{
    ViewBag.Title = "Employee Details";
    var grid = new WebGrid(source: Model, canPage: true, rowsPerPage: 3, canSort: false);
}
<style type="text/css">
    table
    {
        margin: 4px;
        border-collapse: collapse;
        width: 500px;
        font-family: Tahoma;
        font-size: small;
    }
    th
    {
        background-color: #990000;
        font-weight: bold;
        color: White !important;
    }
    table th a
    {
        color: White;
        text-decoration: none;
    }
    #subGrid th
    {
        background-color: #021D39;
    }
    table th, table td
    {
        border: 1px solid black;
        padding: 5px;
    }
    .ExpColl
    {
        cursor: pointer;
    }
    .expand
    {
        background-color: Red;
        width: 10px;
        height: 10px;
    }
    .collapse
    {
        background-color: Green;
        width: 10px;
        height: 10px;
    }
</style>
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        var size = $("#main #mainGrid > thead > tr >th").size();  //get columns size
        $("#main #mainGrid > thead > tr >th").last().remove(); // remove last column
        $("#main #mainGrid > thead > tr").prepend("<th></th>");
        $("#main #mainGrid > tbody > tr").each(function (i, el) {
            $(this).prepend(
                    $("<td><input type='button' value='Get Details' /></td>")
                    .addClass("expand")
                    .addClass("ExpColl")
                );

            var table = $("table", this).parent().html();
            $(this).after("<tr><td></td><td style='padding:5px; margin:0px;' colspan='" + (size - 1) + "'>" + table + "</td></tr>");
            $("table", this).parent().remove();
            $(".ExpColl", this).live("click", function () {
                $(this).parent().closest("tr").next().slideToggle(100);
                $(this).toggleClass("expand collapse");
            });
        });

        $("#main #mainGrid > tbody > tr td.expand").each(function (i, el) {
            $(this).toggleClass("expand collapse");
            $(this).parent().closest("tr").next().slideToggle(100);
        });

    });
</script>
<div id="main" style="padding: 25px; background-color: white;">
    @grid.GetHtml(
    htmlAttributes: new { id = "mainGrid", width = "500px" },
         tableStyle: "webGrid",
         fillEmptyRows: false,
         alternatingRowStyle: "alt",
         headerStyle: "grid-header",
         footerStyle: "foot-grid",
         mode: WebGridPagerModes.All,
         firstText: "<< First",
         previousText: " < Previous",
         nextText: "Next >",
         lastText: "Last >>",
         caption: "User Details",
         emptyRowCellValue: null,
    columns: grid.Columns(
                                    grid.Column("dept.Dept_id", "Dept_id"),
                                    grid.Column("dept.Dept_Name", "Dept_Name"),
            grid.Column(format: (item) =>
            {
                WebGrid subGrid = new WebGrid(source: item.Emp_Details);
                return subGrid.GetHtml(
                    htmlAttributes: new { id = "subGrid" },
                    columns: subGrid.Columns(
                            subGrid.Column("Emp_id", "Emp_id"),
                            subGrid.Column("Emp_Name", "Emp_Name"),
                            subGrid.Column("Address", "Address"),
                            subGrid.Column("Dept_id", "Dept_id")
                        )
                    );
            })
        )
    )
</div>


The output of the above code as shown in the below figure.
When we click on Get Details button then inner Grid will be Expand.
You can download the code by clicking on the below Download button.



No comments:

Post a Comment

© 2012-2014 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.