-->

Treeview in AngularJS application



Introduction

In the previous article, we have seen how to create treeview with database data in MVC application. and how to bind Treeview from database using recursion function in asp.net c#. Here in this article, I will show you how to create treeview in AngularJS for render hierarchical datasets, folder views, and other similar data structures.
In this article, I have used angularTreeview directive for generating treeview from hierarchical data.

Follow the following steps in order to implement "treeview in AngularJS application".

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 MVC template > OK

Step-2: Add a Database.

Now I will create a database for our application. As this is a tutorial project, I will add a database in our application, here in the app_data folder.

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 in our database.

In this example, I would like to render file structure (folder view) of my application in the treeview.So, create a table in our database for store data (hierarchical data).
You can see here in this below image, I have added a column ParentID in our database table. This field is for identifying the parent node. For the item at the top of the treeview, we will fill 0 (ZERO).


double click on the database under app_data folder  for open the database in server explorer > expand the database and Right click on Tables node > click on Add New Table >  here we will write schema of the table for the table we want to create > now click on Update button for create the table and then again click on Update Database button. 

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 an MVC Controller.

If you already have HomeController added in your application (as in the MVC template HomeController is already added), Please skip this step.
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-6: Add required files into our project.

In this article, I am going to use angularTreeview directive. This a very popular directive for render treeview from hierarchical data in AngularJS application.
So, we will download all the required files from github and will add into our application first.
Here I have added following files into our project (you can download from here)
1."angular.treeview.css" file
2."angular.treeview.js" file
3."img" folder

Step-7: Add a partial class of "MyFileStructure" class for adding an additional field for hold child items.

As per angularTreeview document you can see here the example model, here is a field property "children" for identifying child nodes. So we need to add an additional field in our Model. So, I will add a partial class for add an additional field for hold child items.

using System.Collections.Generic;
namespace ngTreeview
{
    public partial class MyFileStructure
    {
        public List<MyFileStructure> Childrens { get; set; }
    }
}

Step-8: Write a recursion method for Recursively get all children's

Now we need to write a recursion method for Recursively get all children's and make our JSON result as per example model, required for angularTreeview directive. So I am going to add the method in the HomeController.
//Recursion method for recursively get all child nodes
public void GetTreeview(List<MyFileStructure> list, MyFileStructure current, ref List<MyFileStructure> returnList)
{
    //get child of current item
    var childs = list.Where(a => a.ParentID == current.ID).ToList();
    current.Childrens = new List<MyFileStructure>();
    current.Childrens.AddRange(childs);
    foreach (var i in childs)
    {
        GetTreeview(list, i, ref returnList);
    }
}

public List<MyFileStructure> BuildTree(List<MyFileStructure> list)
{
    List<MyFileStructure> returnList = new List<MyFileStructure>();
    //find top levels items
    var topLevels = list.Where(a => a.ParentID == list.OrderBy(b => b.ParentID).FirstOrDefault().ParentID);
    returnList.AddRange(topLevels);
    foreach (var i in topLevels)
    {
        GetTreeview(list, i, ref returnList);
    }
    return returnList;
}

Step-9: Add an MVC action into HomeController for fetch data from the database and return as JSON result.

public JsonResult GetFileStructure()
{
    List<MyFileStructure> list = new List<MyFileStructure>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        list = dc.MyFileStructures.OrderBy(a => a.FileName).ToList();
    }

    List<MyFileStructure> treelist = new List<MyFileStructure>();
    if (list.Count > 0)
    {
        treelist = BuildTree(list);
    }

    return new JsonResult { Data = new { treeList = treelist}, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Step-10: Add a javascript file, where we will write AangularJS code for creating an angular module and an angular controller.


In our application, I will add a javascript file into Scripts folder.
Go to solution explorer > Right click on "Scripts" folder > Add > new Item > Select Javascrip file under Scripts > Enter file name (here in my application it is "myApp.js") > and then click on Add button.
var app = angular.module('myApp', ['angularTreeview']);
app.controller('myController', ['$scope', '$http', function ($scope, $http) {
    $http.get('/home/GetFileStructure').then(function (response) {
        $scope.List = response.data.treeList;
    })
}])

Step-11: Add view for that(here Index action) action.

You can see here 1 MVC action Index already added in the HomeController.cs file.
Now we will add a view for that Index action. 
Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select "Empty" under Template dropdown  > > Add.
HTML Code
@{
    ViewBag.Title = "Index";
}
<h2>treeview in angularjs application</h2>
<div ng-app="myApp" ng-controller="myController">
    <span>Selected Node : {{mytree.currentNode.FileName}}</span>
    <div data-angular-treeview="true"
         data-tree-id="mytree"
         data-tree-model="List"
         data-node-id="ID"
         data-node-label="FileName"
         data-node-children="Childrens">
    </div>
</div>
<link href="~/Content/angular.treeview.css" rel="stylesheet" />
@section Scripts{
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
    <script src="~/Scripts/angular.treeview.js"></script>
    <script src="~/Scripts/myApp.js"></script>
}

Step-12: Run Application.

We have done all the steps. Now it's time to run the 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.