Display multilevel nested grid data in asp.net mvc



Introduction

Nowadays display nested grid view (tabular data) is an essential part in web development. There are lots of 3rd party plugin like Telerik grid view for display hierarchy and nested data. But most of the developer avoid 3rd party plugins.

Now in the MVC framework, we have full control over HTML. We can display multilevel hierarchical data without using any 3rd party plugin. In one of my previous article I have shown, how to display grouping data (order and order items) in asp.net MVC application.  Here in this article, we will see how we can display multilevel nested grid view in asp.net MVC application.


Just follow the following steps in order to implement "Displaying multilevel nested grid  data in asp.net MVC".

Here In this article, I have used Visual Studio 2013

Step - 1: Create New Project.

Go to File > New > Project > ASP.NET  Web Application (under web) > Entry Application Name > Click OK > Select Empty template > Checked MVC (under "Add folders and core references for" option) > 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 a table for store data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have created a table (see below image) for store employee data with superior/subordinate relationships in an organization for show multilevel nested grid data.  


Employees Table 

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: Create a custom HTML Helpers.

Here in this application, we have created a custom HTML Helper for generating a table for show multilevel nested grid data.

[N.B. if there is no folder named "App_Code" in your solution, Please follow the step for add App_Code folder. Go to solution explorer > Right click on your project > Add > Add ASP.NET Folder > App_Code.]

Right Click on App_Code folder under Solution Explorer > Add > New Item > Select MVC5 View Page (Rozar) > Enter Name (here "NestedData.cshtml") > Add.
Write this below code to your newly created view under App_Code folder.
@helper GetHtml(List<MVCNestedGrid.Employee> employeeList, int parentID) {
    <table class="table table-bordered">
       @{
           int currentID = 0;
           int rowIndex = 0;
           foreach (var i in employeeList.Where(a=>a.ReportsTo.Equals(parentID)))
           {
               if (i.EmployeeID == currentID)
               {
                   continue;
               }
               else
               {
                   if (rowIndex == 0)
                   {
                       <thead>
                           <tr>
                               <th>Employee ID</th>
                               <th>Employee Name</th>
                               <th>Title</th>
                               <th>Home Phone</th>
                           </tr>
                       </thead>
                   }
                   rowIndex++;
                   currentID = i.EmployeeID;
                   var Sub = employeeList.Where(a => a.ReportsTo.Equals(i.EmployeeID)).ToList();
                   var newEmployeeList = employeeList.Where(a => !a.EmployeeID.Equals(i.EmployeeID)).ToList();
                   <tbody>
                       <tr>
                           <td>
                               @if (Sub.Count > 0)
                               {
                                   <span class="icon icon-e" style="float:left; cursor:pointer;"></span> 
                               }
                               else
                               {
                                   <span style="display:inline-block;width:14px">&nbsp;</span>
                               }
                               @i.EmployeeID
                           </td>
                           <td>@i.TitleOfCourtesy @i.FirstName @i.LastName</td>
                           <td>@i.Title</td>
                           <td>@i.HomePhone</td>
                       </tr>
                       <tr style="display:none;">
                           @if (Sub.Count > 0)
                           {
                               <td colspan="4" class="innerTable">
                                   @NestedData.GetHtml(newEmployeeList, i.EmployeeID)
                               </td>
                           }
                           else
                           {
                                <td colspan="4">

                                </td>
                           }
                       </tr>
                   </tbody>
               }
           }
       }
    </table>
}

Step-6: Create an MVC Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller named "HomeController"

Step-7: Add new action into your controller for show multilevel nested grid data. 

Here I have added "Index" Action into "Home" Controller. Please write this following code
public ActionResult Index()
{
    List<Employee> list = new List<Employee>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        list = dc.Employees.OrderBy(a => a.EmployeeID).ToList();
    }
    return View(list);
}

Step-8: Add an image into our application.

Before design the view, we will add an image in our application for use as collapse/expand icon.
Right Click on project from solution explorer > Add > new folder > Rename "Images" and then Right click on that folder > Add > Existing Item... > select image > Add.

Step-9: Add view for your Action and design.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
HTML Code
@model List<MVCNestedGrid.Employee>
@{
    ViewBag.Title = "Index";
}

<h2>Display multilevel nested grid data in asp.net MVC</h2>
<div class="container">
    @NestedData.GetHtml(Model,0)
</div>

@* CSS *@
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<style>
    .container{min-width:500px; overflow:hidden;}
    .innerTable table{margin:0px auto; border-left-width:4px;}
    td.innerTable {padding-left:20px !important;}
    .icon {
        background-image: url('/images/ui-icons_222222_256x240.png');
        background-repeat:no-repeat;
        width:16px;
        height:16px;
        display:inline-block;
        float:left;
    }
    .icon-e{background-position:-32px -16px}
    .icon-s{background-position:-64px -16px}
</style>
@* Jquery for Collapse/Expend *@
<script type="text/javascript">
    $(document).ready(function () {
        $('.icon').live('click', function () {
            var $pRow = $(this).parents('tr');
            var $nextRow = $pRow.next('tr');
            $nextRow.toggle();
            $(this).toggleClass('icon-s icon-e');
        });
    })
</script>

Here I have created two React components named "EmployeeGridTable" and "EmployeeGridRow".

Step-10: Run Application.


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.