Email: Password:       Forgot Password 
    .netCodeSG
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.
 
TECHNOLOGIES:
 

ASP.NET MVC4 - Showing DATA in Nested Grid View using jQuery

Article:
Viewed:  3328 
Posted On:  6/3/2015 8:26:55 PM 
How we can show our data as nested Grid View in ASP.NET MVC 4 application? 

Here in this article I am going to show how we can display our data in nested Grid View. Mean I have 2 below tables.

1.    Project

1.png

Image 1.

Script of My Table is:

CREATE TABLE [dbo].[Project](
          [ProjectID] [int] IDENTITY(1,1) NOT NULL,
          [ProjectName] [varchar](50) NULL,
          [ProjectLeader] [varchar](50) NULL,
 CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
          [ProjectID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET ANSI_PADDING OFF
GO


2. Employee:

2.png

Image 2.

Script of my Employee table is:

CREATE TABLE [dbo].[Employee](
          [ID] [int] IDENTITY(1,1) NOT NULL,
          [Name] [varchar](50) NULL,
          [Email] [varchar](500) NULL,
          [Country] [varchar](50) NULL,
          [ProjectID] [int] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
(
          [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON
PRIMARY]
) ON [PRIMARY]
 
GO
SET ANSI_PADDING OFF
GO
 
 

Now create a new Visual Studio Project.

3.png

Image 3.

4.png

Image 4.

Now right click on Project solution Explorer -> Add New ADO.NET Entity Data Model:

5.png

Image 5.

6.png

Image 6.

7.png

Image 7.

8.png

Image 8.

9.png

Image 9.

10.png

Image 10.

Now see Data in my these 2 (Project & Employee Tables)

11.png

Image 11.

12.png

Image 12.

Now Right Click on Model folder inside your project's Solution Explorer -> Add New Item-> Add New Class-> EmpProject.cs

13.png

Image 13.

Do below code here:

14.png

Image 14.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace ShowingNestedDataDisplayInMVC4.Models
{
    public class EmpProject
    {
        public Project project { get; set; }
        public List<Employee> projectEmployee { get; set; }
    }
}

Now Right Click on Controller -> Add New Controller

15.png

Image 15.

16.png

Image 16.

Now Here in Project Controller do the below code:

17.png

Image 17.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShowingNestedDataDisplayInMVC4.Models;
 
namespace ShowingNestedDataDisplayInMVC4.Controllers
{
    public class ProjectController : Controller
    {
        //
        // GET: /Project/
        public ActionResult Index()
        {
            List<EmpProject> prjEMPReport = new List<EmpProject>();
 
            // here MyDatabaseEntities is our data context
            using (EmployeeProjectEntities dc = new EmployeeProjectEntities())
            {
                var prjRecords = dc.Project.OrderByDescending(a => a.ProjectID);
                foreach (var i in prjRecords)
                {
                    var empPrjDTL = dc.Employee.Where(a => a.ProjectID == (i.ProjectID)).ToList();
                    prjEMPReport.Add(new EmpProject { project = i, projectEmployee = empPrjDTL });
                }
            }
            return View(prjEMPReport);
        }
    }
}

Now Right Click On Index Action Method -> Add View

18.png

Image 18.

In Index.cshtm do the below code:

@model IEnumerable<ShowingNestedDataDisplayInMVC4.Models.EmpProject>
@{
    ViewBag.Title = "Displaying Data In Nested Grid View In MVC4";
    WebGrid grid = new WebGrid(source: Model, canSort: false);
}
 
<style>
    #gridT, #gridT tr {
        border: 1px solid #0D857B;
    }
    #nestedT, #nestedT tr {
        border: 1px solid #f3f3f3;
    }
    #nestedT {
        margin: 0px 0px 0px 10px;
        padding: 5px;
        width: 95%;
    }
        #nestedT th {
            font-size: 14px;
            font-weight: bold;
            background-color: green;
        }
    .recordHoverEffect {
        cursor: pointer;
    }
 
        .recordHoverEffect:hover {
            background-color: rgb(248, 242, 242);
        }
 
    .expandRecordRecord {
        background-image: url(/Images/ShowHideImage.png);
        background-position-x: -22px;
        background-repeat: no-repeat;
    }
 
    .collapseRecordRecord {
        background-image: url(/Images/ShowHideImage.png);
        background-position-x: -2px;
        background-repeat: no-repeat;
    }
</style>

@section Scripts{
    <script>
        $(document).ready(function () {
            var size = $("#main #gridT > thead > tr >th").size();
            $("#main #gridT > thead > tr >th").last().remove();
            $("#main #gridT > thead > tr").prepend("<th></th>");
            $("#main #gridT > tbody > tr").each(function (i, el) {
                $(this).prepend(
                        $("<td></td>")
                        .addClass("expandRecord")
                        .addClass("recordHoverEffect")
                        .attr('title', "Show Hide Details")
                    );

                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();
 
                $(".recordHoverEffect", this).live("click", function () {
                    $(this).parent().closest("tr").next().slideToggle(100);
                    $(this).toggleClass("expandRecord collapseRecord");
                });
            });
 
 
            $("#main #gridT > tbody > tr td.expandRecord").each(function (i, el) {
                $(this).toggleClass("expandRecord collapseRecord");
                $(this).parent().closest("tr").next().slideToggle(100);
            });
 
        });
    </script>
}

<div id="main" style="padding: 25px; background-color: yellow;">
    @grid.GetHtml(
                htmlAttributes: new { id = "gridT", width = "900px", style = "background-color:skyblue; color:blue;
                                               font-size:14pt; font-family:TimesNewRoman;"
},
                columns: grid.Columns(
                        grid.Column("project.ProjectID", "Project ID"),
                        grid.Column("project.ProjectName", "Project Name"),
                        grid.Column("project.ProjectLeader", "Project Leader"),
 
                        grid.Column(format: (item) =>
                        {
                            WebGrid subGrid = new WebGrid(source: item.projectEmployee);
                            return subGrid.GetHtml(
                                htmlAttributes: new { id = "nestedT", style = "background-color:red; color:white; font-size:12pt; font-family:verdana;" },
                                columns: subGrid.Columns(
                                        subGrid.Column("ID", " Employee ID"),
                                        subGrid.Column("Name", "Name"),
                                        subGrid.Column("Email", "Email"),
                                        subGrid.Column("Country", "Country")
                                    )
                                );
                        })
                    )
                )
</div>
 

You can set your view as start up For This open Route.config inside App_Start Folder and do below setting:

19.png

Image 19.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
 
namespace ShowingNestedDataDisplayInMVC4
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Project", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}


Now time to run your application:

20.png

Image 20.

Now got to Project ID to expand the details of this project:

21.png

Image 21.

22.png

Image 22.

23.png

Image 23.

24.png

Image 24.

 

25.png

Image 25.

26.png

Image 26.

  Comment:
         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us