Click here to Skip to main content
15,881,092 members
Articles / Web Development / ASP.NET
Tip/Trick

How to Create TreeView in MVC3

Rate me:
Please Sign up or sign in to vote.
5.00/5 (11 votes)
15 Dec 2013CPOL4 min read 97.5K   8.2K   15   8
How to create TreeView in MVC

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<code>.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.

C#
OrganizationEntities _orgDb = new OrganizationEntities(); 

Image 1

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.

C#
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.

C#
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.

C#
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:

Image 2

Now let's start building our tree.

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

HTML
@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:

HTML
@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.

JavaScript
    <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)


Written By
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

Comments and Discussions

 
QuestionWorked Pin
m.elabbady20-Feb-18 9:17
m.elabbady20-Feb-18 9:17 
QuestionIt works with one record Pin
Member 123769173-Apr-17 2:56
Member 123769173-Apr-17 2:56 
GeneralGood This one helped Pin
Nithin Paul3-Feb-16 21:49
Nithin Paul3-Feb-16 21:49 
Questionki banaichos ???? kaj kore na , dhur mea. Pin
Member 114467851-Aug-15 19:57
Member 114467851-Aug-15 19:57 
Dear sir

its not working for me, faltu jinis banaichis
QuestionExpand/Collapse Pin
Member 118168027-Jul-15 2:42
Member 118168027-Jul-15 2:42 
QuestionHow-to-Create-TreeView-in-MVC Pin
Pkay2221-Apr-15 5:04
Pkay2221-Apr-15 5:04 
Questioncan I do it with using jstree? Pin
Member 110520201-Sep-14 23:04
Member 110520201-Sep-14 23:04 
GeneralMy vote of 5 Pin
Member 1098068211-Aug-14 1:54
Member 1098068211-Aug-14 1:54 

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.