Create Tree-view in JQuery using jsTree Plugin From Nested JSON Data

Treeview is a structure we mostly use to represent parent-children data for better observation.

But when it comes to ASP.NET development there is a server side control named treeview for it. But I am sure it's not that efficient now-a-days when everything is being done in front-end side by JavaScript frameworks we never gonna use this one.
There are many Jquery plugins available in the internet to create TreeView but I find jsTree very intuitive and easy to use.

There are few articles a good documentation on it in their site but I still found those not sufficient enough to get started with jsTree when you are using it for the first time. So I came up with an idea to create a series of blogs on jsTree that can help people who are trying to figure it out and want to use jsTree in their ASP.NET applications.

Find out all the articles on jsTree here.

Tree View Example
Before we get into the details of jsTree and its implementations you need to download the js and css files for it. Download jsTree plugin from here.


View Live Demo


Setting up a Project and adding jsTree resources


Now create a project in visual studio and add the jstree-src folder inside it, that you got from the download.

Contents of jsTree folder



The folder has two themes one is default and one is a darker one. You can use those according to your need. Now lets add the js and css references to your web page.

<script src="js/jquery.min.js"></script>
<script src="jstree-src/jstree.min.js"></script>

<link href="jstree-src/themes/default/style.css" rel="stylesheet" />
You also need to add a jquery reference in your page in order to use the jsTree plugin.

Creating container for the jsTree


Below is the html I have used in my demo project, but you might not want to use the entire html. Just use the container to populate the jsTree.
<div role="tabpanel" class="tab-pane active p-20-0" id="preview" aria-labelledby="preview-tab">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h3 class="panel-title">Nested JSON Example Data</h3>
            </div>
            <div class="panel-body">
                <div class="m-b-10">
                    <asp:TextBox ID="txtSearchXML" runat="server" placeholder="Serch JSTree" CssClass="search-input form-control"></asp:TextBox>
                </div>

                <div id="jstree-xml">
                </div>
            </div>
            <div id="footer-xml" class="panel-footer">You have not selected any node</div>
        </div>
    </div>
You just need the below container for jsTree.
<div id="jstree-xml"> </div>

 Now lets feed the jsTree with JSON Data


The jsTree will work on only JSON data and it has two predefined structure, in which the JSON will be accepted.
  1. JSON with nested elements (parent-children structure)
  2. JSON with flat structure (with parent id structure)
The first one JSON with nested elements is a bit difficult to produce when you are using a database so I prefer using the second one as its pretty simple and easy because of its flat structure.



But in this article we will use the first json format i.e JSON with nested element to populate the jsTree. Below is the JSON format.
var jsonData = [
      {
          id: 1,
          text: "Folder 1",
          state: {
              selected: false
          },
          children: [
            {
                id: 2,
                text: "Sub Folder 1",
                state: {
                    selected: false
                },
                children: [
                     {
                         id: 3,
                         text: "Sub - Sub Folder 1",
                         state: {
                             selected: true
                         },
                         children: []
                     }
                ],
            },
            {
                id: 4,
                text: "Sub Folder 2",
                state: {
                    selected: false
                },
            }
          ]
      },
      {
          id: 5,
          text: "Folder 2",
          state: {
              selected: false
          },
          children: []
      }
    ];
Now we will initiate the jsTree with required attributes.
$('#jstree-xml').jstree({
        'core': {
            'data': jsonData
        },
        "types": {
            "child": {
                "icon": "glyphicon glyphicon-leaf"
            },
            "root": {
                "icon": "glyphicon glyphicon-folder-close"
            },
            "default": {
                "icon": "glyphicon glyphicon-folder-close"
            }
        },
        "search": {

            "case_insensitive": true,
            "show_only_matches": true


        },

        "plugins": ["search", "themes", "types"]
    });
If you look into the above code you can find below attributes

core: this is taking the json data in the variable data. this is where we will attach ajax functions in our next articles to feed the jstree with json data.




type: this is the attribute that is responsible for styling nodes. If a node is of type root then the defined style will be applied to it and if of child then the specified style for child type will be added to that node.

search: this says about the search feature options if its case sensitive or not and all.

In the next section we will set up a search feature in the jsTree and the code is below. I have taken a textbox and will search the jsTree on keyUp function. You can customize it according to your need. You may take a textbox and a button and on click of it you can perform a search or whatever you want.
$("#txtSearchXML").keyup(function () {
        var searchString = $(this).val();
        console.log(searchString);
        $('#jstree-xml').jstree('search', searchString);
    });
And  now we will write another function to get the selected node information. Below is the code to get the selected node information of the jsTree.
$('#jstree-xml').on('changed.jstree', function (e, data) {
        var objNode = data.instance.get_node(data.selected);
        var note;

        note = 'Selected Node Data(Id: <strong>' + objNode.id + '</strong>, Name: <strong>' + objNode.text + '</strong>)';

        $('#footer-xml').html(note);
    });
Here I am getting the node information and printing it on the panel footer.

If you are looking for the whole jquery function to load the jsTree with nested JSON data then here it is.
function LoadJSTreeWithNestedJSONData() {

    $('#jstree-xml').jstree({
        'core': {
            'data': jsonData
        },
        "types": {
            "child": {
                "icon": "glyphicon glyphicon-leaf"
            },
            "root": {
                "icon": "glyphicon glyphicon-folder-close"
            },
            "default": {
                "icon": "glyphicon glyphicon-folder-close"
            }
        },
        "search": {

            "case_insensitive": true,
            "show_only_matches": true


        },

        "plugins": ["search", "themes", "types"]
    });

    $("#txtSearchXML").keyup(function () {
        var searchString = $(this).val();
        console.log(searchString);
        $('#jstree-xml').jstree('search', searchString);
    });

    $('#jstree-xml').on('changed.jstree', function (e, data) {
        var objNode = data.instance.get_node(data.selected);
        var note;

        note = 'Selected Node Data(Id: <strong>' + objNode.id + '</strong>, Name: <strong>' + objNode.text + '</strong>)';

        $('#footer-xml').html(note);
    });
}

View Live Demo

That's it you have created a jsTree with nested JSON data. Check out my next article on creating jsTree with flat JSON data. And all articles on JsTree here.

Happy Codding...

No comments:

Post a Comment