Click here to Skip to main content
Click here to Skip to main content

How to Create TreeView in MVC3

By , 15 Dec 2013
Rate this:
Please Sign up or sign in to vote.

Introduction

This is a simple tutorial to explain how to use jsTree in MVC3 to create treeview in MVC. MVC does not support server side ASP.NET control like ASP.NET. MVC3 specially contains HTML helper class and Ajax class to support UI design. There is no helper class method that will provide treeview for the UI. In this tutorial, I will demonstrate how to create treeview in MVC3 using jsTree plugin. I have not explained how to use jsTree plugin because that is done better in jquery side. I request you to download jsTree plugin and read how to use the plugin from here.

Answer

Create MVC3 empty project by selecting view engine as the Razor view. Add Home Controller and Index Action. I have Database name Organization in my App_Data folder. For demo purposes, I have added Employee table in my database.

My intention is to create a simple employee table with name and employee code and employee reporting filed where employee reporting filed contain the employee code of the reporting manager. As one of the Employees is supreme in organization, he did not report to anyone. You can look at the following table data:

Employee CodeEmployee NameReporting
Emp1RajuNULL
Emp2AmeyEmp1
Emp3PushkarEmp1
Emp4RameshEmp3
Emp5SureshEmp4

I have created this table on a favorite example of self join to find out the employee who is manager, i.e., to use self join on this table to find out the employee and their reporting employee name.

But I will do a little trick here and create a list of employees according to the hierarchy of employees in the organization as follows:

I have created ADO.NET entity data model name Organization.edmx as my Model in Model folder of MVC project. I have created Business class EmployeeManager that contains method name GetTreeVeiwList() that will return us the list of employees by organization hierarchy.

Let's build pseudo code to find out the actual functioning of the GetTreeVeiwList() function.

Step 1: Create Employee object emp.

Step 2: Find out the employee who is the supreme manager who does not report to anyone.

Step 3: Assign to the emp object.

Step 4: If emp manages one or more than one employee, go to the next step, else stop.

Step 5: Find employee list, i.e., list of emp and assign as child node to emp object.

Step 6: Send each child node, i.e., emp object to the step 4.

I have instantiated the Entities context object name _orgDb.

OrganizationEntities _orgDb = new OrganizationEntities(); 

I have created the TreeViewNodeVM class as ViewModel that contains the tree view structure data to display on the View Page. This is the emp object of our pseudo code. and ChildNode represents the list of emp object from our pseudo code.

    public class TreeViewNodeVM
    {
        public TreeViewNodeVM()
        {
            ChildNode = new List<TreeViewNodeVM>();
        }

        public string EmployeeCode { get; set; }
        public string EmployeeName { get; set; }
        public string NodeName
        {
            get { return GetNodeName(); }
        }
        public IList<TreeViewNodeVM> ChildNode { get; set; }

        public string GetNodeName()
        {
            string temp = ChildNode.Count > 0 ? "    This employee manages " + 
            ChildNode.Count : "    This employee is working without westing time in managing.";
            return this.EmployeeCode + "  " + this.EmployeeName + temp;
        }
    } 

Let's retrieve a record of employees who is the supreme authority that does not report to anyone may be organization owner having reporting field as null. This employee contains one root of the tree specifying supreme manager that does not report to any one.

        public TreeViewNodeVM GetTreeVeiwList()
        {
            TreeViewNodeVM rootNode = (from e1 in _orgDb.Employees
                                       where e1.Reporting == null
                                       select new TreeViewNodeVM()
                                       {
                                           EmployeeCode = e1.Emp_Code,
                                           EmployeeName = e1.Name
                                       }).SingleOrDefault();
            BuildChildNode(rootNode);

            return rootNode;
        }  

I have created function BuildChidNode(Employee emp) that will take the Employee who is Manager and provide list of employees that report to that manager. And assign employee list to the ChildNode. Childnode represents list of employee. Each employee in child node might be manager of another employee and so on. I have called the BuildChildnode method nested for each employee to find out list of employee he manages. There are employees who do not manage anyone, i.e., they represent root of the tree and our nested function nesting end there.

        private void BuildChildNode(TreeViewNodeVM rootNode)
        {
            if (rootNode != null)
            {
                List<TreeViewNodeVM> chidNode = (from e1 in _orgDb.Employees
                                                  where e1.Reporting == rootNode.EmployeeCode
                                                  select new TreeViewNodeVM()
                                                  {
                                                      EmployeeCode = e1.Emp_Code,
                                                      EmployeeName = e1.Name
                                                  }).ToList<TreeViewNodeVM>();
                if (chidNode.Count > 0)
                {
                    foreach (var childRootNode in chidNode)
                    {
                        BuildChildNode(childRootNode);
                        rootNode.ChildNode.Add(childRootNode);
                    }
                }
            }
        } 

We will get the TreeView Node as follows:

Now let's start building our tree.

Create strongly type Index View of type TreeViewNodeVM [ViewModel]. Create Html tag as follows:

@model TreeViewDemo.ViewModel.TreeViewNodeVM
@{

    ViewBag.Title = "Index";
}
<h2>
    Tree View Demo!!!</h2>
<div id="treeDemo">
    <ul id="tree">
        <li>
            <a href="#">@Model.NodeName</a>
            @Html.Partial("ChildNode", Model.ChildNode)
        </li>
    </ul>
</div> 

We will specify the supreme manager, i.e., root node in this view and call the partial view to display child node. If child node contains child node, we will call nested partial view to display them as follows:

@model IEnumerable<TreeViewDemo.ViewModel.TreeViewNodeVM>
@foreach (var treeNode in Model)
{
    <ul>
        @if (treeNode != null)
        { 
            <li><a href="#">
                @treeNode.NodeName
            </a>
                @if (treeNode.ChildNode.Count > 0)
                {
                    @Html.Partial("ChildNode", treeNode.ChildNode)
                }
            </li> 
        }
    </ul>
} 

Let's add the jquery to create jsTree.

    <script src="@Url.Content("~/Scripts/jquery-1.10.2.min.js")" 
type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jstree.js")" 
    type="text/javascript"></script>

    <link href="../../Scripts/themes/style.css" 
    rel="stylesheet" type="text/css" 

    <script type="text/javascript">
        $(function () {
            $('#treeDemo').jstree();
        });
    </script> 

We have selected the div with id treeDemo as our treeview container which contains unordered list with id tree that will be converted into the treeview. Rest of the magic is done by the jsTree plugin. You can customize your jsTree based on your requirement by modifying /themes/style.css. This ends our simple demo of jsTree. Hope you enjoyed this demo.

License

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

About the Author

Amey K Bhatkar
Web Developer Lionbridge
India India
Amey K Bhatkar, a “Microsoft .Net” Web Developer.
I am programmer by will and profession.
I have completed my MCA in 2011 and join software industry.
Presently I am working with Lion Bridge Technologies in Mumbai - India
Follow on   Twitter   Google+

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140421.2 | Last Updated 16 Dec 2013
Article Copyright 2013 by Amey K Bhatkar
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid