Click here to Skip to main content
15,885,435 members
Articles / Web Development / HTML
Tip/Trick

Drilldown Hierarchical Data Using MVC and JQuery

Rate me:
Please Sign up or sign in to vote.
4.83/5 (4 votes)
1 Dec 2014CPOL5 min read 35.8K   1.1K   15   8
Microsoft’s Model-View-Controller with Razor View Engine and JQuery make drill-down hierarchal data very easy to develop for web application.

Introduction

I believe you came across so many times that your application must display hierarchical data to user in tabular form and allow user to drilldown data for detail information. User loves to analyze data in tabular form instead of hoping around different pages.

To implement drill down functionality for tabular data, you may spend huge number of hours to develop it or lots of money to buy a third party tools. Microsoft’s Model-View-Controller with Razor View Engine and JQuery makes it very easy that you can build a drill down tabular data in few minutes.

In this topic, I will walk you through how to create a MVC application to drill down tabular data. Please note that I am concentrating on the functionality instead of making it nice. In this demonstration, I am going to use Student object for student information. Student object will contain Course object for course description.

Create MVC 4 Web Application

Using Visual Studio 2012, create a new project with MVC 4 Web Application. Select the template either Internet or Intranet application. I have selected the Internet Application Template. Make sure Razor is selected in the View Engine.

By default, Visual Studio will create several files for Controllers, Models and Views. In this demo, we are going to modify the landing page of the application. In other words, we are going to use the Index.cshtml view to display our Student data.

As a first step for cleanup, open the Index.cshtml and delete all lines of code and save the file. We will update it with our code later.

Add JQuery Scripts to Project

Open the _Layout.cshtml from the Views->Shared folder and add the following JQuery references just before the end tag (</head>) of Head.

HTML
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>

Create Data Model (Student and Course)

From the Solution Explorer, right click on the Models and select Add option from context menu. Then select Class option and name it Student. Now, the Models folder should have the Student.cs class. Similarly, create another class and name it Course.

Open Student.cs and add fields. You may add validation and others attribute. To concentrate only on the drilldown, I kept it simple.

C#
namespace DrillDownDemo.Models
{
    public class Student
    {
        public int ID { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Address { get; set; }
        public String email { get; set; }
        public String Department { get; set; }
        public List<Course> Courses = new List<Course>();
    }
}

Open Course.cs and add fields:

C#
namespace DrillDownDemo.Models
{
    public class Course
    {
        public String CourseName { get; set; }
        public String SemesterName { get; set; }
    }
}

Modify Controller (HomeController)

For this demo application, as we are using the landing page, we need to modify HomeController. In real life application, you may need to display the data in different view. In that case, you will need to add/modify the corresponding controller.

Here we are using static data, instead of using backend data storage. Add a static list of Student object which contains Course object in the HomeController.

C#
public static List<Models.Student> Students = new List<Models.Student>()
            {
                new Models.Student
                { ID = 1, FirstName = "Jhon", LastName = "Smith", 
                            Courses = new List<Models.Course>()
                            {
                                new Models.Course { ID = 1, 
                            CourseName = "CS 101",
                            SemesterName = "Winter 2010"
                          },
                                new Models.Course { ID = 2, 
                            CourseName = "MATH 102",
                             SemesterName = "Fall 2010"
                          },
                                new Models.Course { ID = 3, 
                            CourseName = "ENG 103",
                            SemesterName = "Winter 2011"
                          },
                                new Models.Course { ID = 4, 
                            CourseName = "EE 104",
                            SemesterName = "Fall 2012"
                          }
                            }
                },
                new Models.Student
                { ID = 2, FirstName = "Jorge", LastName = "Garcia", 
                            Courses = new List<Models.Course>()
                            {
                                new Models.Course { ID = 5, 
                            CourseName = "CS 205",
                            SemesterName = "Winter 2010"
                          },
                                new Models.Course { ID = 6, 
                            CourseName = "MATH 206",
                            SemesterName = "Fall 2010"
                          },
                                new Models.Course { ID = 7, 
                            CourseName = "ENG 207",
                            SemesterName = "Winter 2011"
                          },
                                new Models.Course { ID = 8, 
                            CourseName = "EE 208",
                            SemesterName = "Fall 2012"
                          }
                            }
                },
                new Models.Student
                { ID = 3, FirstName = "Gorge", LastName = "Klene", 
                            Courses = new List<Models.Course>()
                            {
                                new Models.Course { ID = 9, 
                            CourseName = "CS 301",
                            SemesterName = "Winter 2010"
                          },
                                new Models.Course { ID = 10, 
                            CourseName = "MATH 302",
                            SemesterName = "Fall 2010"
                          },
                                new Models.Course { ID = 11, 
                            CourseName = "ENG 303",
                            SemesterName = "Winter 2011"
                          },
                                new Models.Course { ID = 12, 
                            CourseName = "EE 304",
                            SemesterName = "Fall 2012"
                          }
                            }
                }
};

Modify the View (index.cshtml)

Adding HTML to Display Data

Open Index.cshtml file from the Views->Home folder. First, we need to specify the Data Model for this view. At the first line of the Index.cshtml file, add the following:

C#
@model IEnumerable<DrillDownDemo.Models.Student>

If you like, you may add the ViewBag.Title as follows:

C#
@{
    ViewBag.Title = "Drill Down Demo";
} 

Next, we need to design the tabular data. In this case, we will have Student as the main rows and we will drill down to Course from Student. Our final output will be like the following image:

Image 1

Now, define the table with Header as follows:

HTML
<table>
     <tr>
            <th>Action</th>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Address</th>
            <th>email</th>
            <th>Department</th>
        </tr>
</table>

Populate data for each Student by adding @foeach statement before the end tag of table as follows:

C#
@foreach (var s in Model)
{
            <tr style="background-color: #00CCFF; color: #FFFFFF;">
                <td>
                    <a href="#" class="collapse expand-btn">Expand</a>
                    <a href="#" class="expand collapse-btn">Collapse</a>
                </td>
                <td>
                    @Html.DisplayFor(p=>s.ID)
                </td>
                <td>
                    @Html.DisplayFor(p=>s.FirstName)
                </td>
                <td>
                    @Html.DisplayFor(p=>s.LastName)
                </td>
                <td>
                    @Html.DisplayFor(p=>s.Address)
                </td>
                <td>
                    @Html.DisplayFor(p=>s.email)
                </td>
                <td>
                    @Html.DisplayFor(p=>s.Department)
                </td>
            </tr>
}

Please note that in the first column of the above code segment, I have added two hyperlinks. First one shows the “Expand” text so that user can click on this and see Course information. Other one collapses the Course information.

There are two classes in each class attribute of those hyperlinks. For example, Expand link has “collapse” and “expand-btn”. These two classes will be used to control the drill down. We don’t need to define those as a style (CSS file). These will be used by JQuery method to find the proper Student row to display or hide the content and also for handling click event. More detail will be described in the JQuery section.

We need to add the code to display course for each student. Hence, add the following code before the end curly brace (“}”) of @foreach loop mentioned above in the code.

HTML
<tr id ="@s.ID" class="expand collapse">
    <td></td>
        <td colspan="4">
        <table>
                        <tr>
                            <th>Course ID</th>
                            <th>Course Name</th>
                            <th>Semester</th>
                        </tr>
                        @foreach (var course in s.Courses)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(p=>course.ID)
                                </td>
                                <td>
                                    @Html.DisplayFor(p=>course.CourseName)
                                </td>
                                <td>
                                    @Html.DisplayFor(p=>course.SemesterName)
                                </td>
                            </tr>
                       
                        }
        </table>
        </td>
    <td></td>
</tr>

You may notice that I have added another table row in the original table I created before. Inside that table row, I added another table with header for Course information. Then, I added the @foreach to display all courses for a student.

In the table row mentioned above, I have added two class attributes – “expand” and “collapse”. Those will be used in the JQuery method to hide or display course information. More detail will be explained the JQuery section.

Before adding JQuery, we may run the application and see the data. It shows all students and courses in expanded mode. Here is an image of how data looks like up to this point. Next, we are going to add JQuery functions to hide or display data.

Image 2

Adding JQuery Method

We are going to use JQuery to control the Drilldown by hiding or displaying Course Information as well as the Action columns of Student Information row. After adding all of the HTML mentioned above, add a <script> section as follows:

HTML
<script type="text/javascript">
  $(function(){
    $('.expand').hide();      // Default - hide the table row of Course information
                // and also hide the Collapse text from 
                // Student information's action column

    $('.expand-btn, .collapse-btn').on("click", function(){
    var tr = $(this).parents('tr:first');
    tr.find('.expand, .collapse').toggle();    // toggle to display either Expand or
                        // Collapse text in the Student row

    tr.next().toggle();    // toggle to display table row with Course information
    });
  });
</script>

The first statement $('.expand').hide(); finds all of the tags in the document which has class attribute “expand” and hides them. This will hide the “Collapse” text from Student record and also hide the Course information. Because, if you look back at the view’s code, you can see the “Collapse” action text and table row in the Student table have class attribute “expand”.

Next, we need to define a function which will be activated when user clicks on “Expand” or “Collapse” text under the Action column of Student record. In this method, it finds the Student row of the clicked Action (Expand or Collapse Text) and toggles the Action text. For example, at the beginning, Student row shows Expand action. When user click on Expand, it will hide Expand and show Collapse so that user can click on it to collapse the Course information.

Next, it finds the row, which contains the Course information and also toggles it between hide and display the row.

Conclusion

MVC and JQuery together make it very easy to implement Drilldown hierarchical data.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
Team Lead and Application Developer in a wide variety of business application development. Particularly, interested in team managing and architecting application. Always, interested in solving complex problem.

Specialties: Team management, Agile, .Net Framework, Java, Database Design, MVVM, MVC, Enterprise Library, Prism

Comments and Discussions

 
QuestionReal db data Pin
Member 830203317-Mar-16 13:21
Member 830203317-Mar-16 13:21 
GeneralGood Pin
enterprisetoday7-Dec-14 16:39
professionalenterprisetoday7-Dec-14 16:39 
Suggestionstumped on your code download Pin
tutor2-Dec-14 8:33
tutor2-Dec-14 8:33 
GeneralRe: stumped on your code download Pin
Pinakpani Dey2-Dec-14 11:11
professionalPinakpani Dey2-Dec-14 11:11 
GeneralRe: stumped on your code download Pin
tutor3-Dec-14 2:14
tutor3-Dec-14 2:14 
GeneralRe: stumped on your code download Pin
Pinakpani Dey3-Dec-14 2:38
professionalPinakpani Dey3-Dec-14 2:38 
GeneralRe: stumped on your code download Pin
tutor3-Dec-14 3:00
tutor3-Dec-14 3:00 
GeneralRe: stumped on your code download Pin
Pinakpani Dey5-Dec-14 2:36
professionalPinakpani Dey5-Dec-14 2:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.