• Now Online : 25
  • admin@codemyne.net

Introduction

jsTree is a jquery plugin which is used to populate hierarchies in treeview. The advantage of using jsTree is it can be bind to diffrent objects like html, json, xml. The checkbox plugin of jsTree makes multiselection possible using three-state checkboxes. More over it can be bind to static data or dynamic data.

In this article the jsTree is bind to json object data. The json object which is to be bind to jsTree should follow the format as shown below.


  var data = [{ "id": 1, "data": "Category", "attr": { "id": "1", "selected": false }, "children":
[
    { "id": 2, "data": "SubCategory1", "attr": { "id": "2", "selected": false }, "children":
            [{ "id": 4, "data": "Item1", "attr": { "id": "4", "selected": false }, "children": [] },
                { "id": 5, "data": "Item2", "attr": { "id": "5", "selected": false }, "children": [] },
                { "id": 6, "data": "Item3", "attr": { "id": "6", "selected": false }, "children": [] }
            ]
    },
    { "id": 3, "data": "SubCategory2", "attr": { "id": "3", "selected": false }, "children":
                [{ "id": 7, "data": "Item4", "attr": { "id": "7", "selected": false }, "children": [] },
                { "id": 8, "data": "Item5", "attr": { "id": "8", "selected": false }, "children": [] },
                { "id": 9, "data": "Item6", "attr": { "id": "9", "selected": false }, "children": [] }
                ]
    }
]
}];

you can bind the above json object to jsTree. So that you can form a static treeview. But the aim of this article is how to bind dynamic data to jsTree. For this the technic which is explained in one other artcile is applying here. You can find that article here. Flat data hierarchical data using Csharp and Linq. The json format shown above can be produced by doing small changes to the code expalined in this article.

Follow the steps as explained to form treeview with checkboxes using json data.

Step 1: Create a new MVC 3 Razor Project and add a controller and view with a name 'Home' and add a div as below.

<div id="onflycheckboxes">
</div>

Step 2: Then add the below script at the end of the document before html close tag.

<script type="text/javascript">
    $(function () {
        FillJSTree();
    });
        function FillJSTree() {
        $("#onflycheckboxes").jstree({
            json_data: {
                    "ajax": {
                    "url": "/Home/GetTreeData",
                    "type": "POST",
                    "dataType": "json",
                    "contentType": "application/json charset=utf-8"
                }
            },
            checkbox: {
                real_checkboxes: true,
                checked_parent_open: true
            },
            plugins: ["themes", "json_data", "ui", "checkbox"]
        });
    }   
</script>
<script src="@Url.Content("~/Scripts/jquery.jstree.js")" type="text/javascript"></script>

Step 3: Create a class file in models folder and add classes to this file as shown below

  public class FlatObject
{
    public Int64 Id { get; set; }
    public Int64 ParentId { get; set; }
    public string data { get; set; }
    public FlatObject(string name, Int64 id, Int64 parentId)
    {
        data = name;
        Id = id;
        ParentId = parentId;
    }
}
public class RecursiveObject
{             
    public string data { get; set; }
    public Int64 id { get; set; }  
    public FlatTreeAttribute attr { get; set; }
    public List<RecursiveObject> children { get; set; }
}
public class FlatTreeAttribute
{
    public string id;
    public bool selected;
}

Step 4: Now add the below code to homecontroller.

        public string GetTreeData()
{
    List<FlatObject> flatObjects = new List<FlatObject>
{
    new FlatObject("Category",1,0),   
    new FlatObject("SubCategory1",2,1), 
    new FlatObject("SubCategory2",3,1), 
    new FlatObject("Item1",4,2), 
    new FlatObject("Item2",5,2),             
    new FlatObject("Item3",6,2),
    new FlatObject("Item4",7,3),
    new FlatObject("Item5",8,3),
    new FlatObject("Item6",9,3)
            
};
    var recursiveObjects = FillRecursive(flatObjects, 0);
string myjsonmodel = new JavaScriptSerializer().Serialize(recursiveObjects);
return myjsonmodel;
}
private static List<RecursiveObject> FillRecursive(List<FlatObject> flatObjects, Int64 parentId)
{
    List<RecursiveObject> recursiveObjects = new List<RecursiveObject>();
    foreach (var item in flatObjects.Where(x => x.ParentId.Equals(parentId)))
    {
        recursiveObjects.Add(new RecursiveObject
        {
            data = item.data,
            id = item.Id,
            attr = new FlatTreeAttribute { id = item.Id.ToString(), selected = false },
            children = FillRecursive(flatObjects, item.Id)
        });
    }
    return recursiveObjects;
}

About above steps: The first and second steps creates a mvc3 razor project and adds a div. In next step in .jstree function has jquery ajax post method which calls an action named 'GetTreeData' from homecontroller. The treeview is populated with checkboxes by using a plugin 'checkbox'.

The 'GetTreeData' action returns a json serialized object which is converted into a json object with the use of 'FillRecursive' method in homecontroller.

'FillRecursive' method in homecontroller converts the original flat object into hierarchical object with the use of class 'RecursiveObject' in models. Thus you can create a dynamic treeview with checkboxes in MVC 3 Razor.

To get checked values for jsTree: The following call can retrieve the checked values for jsTree.

divId = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
    (function () {
        divId.push(this.id);              
});

To get checked boxes text for jsTree: The following call can retrieve the checked values for jsTree.

 
divText = [];
$("#onflycheckboxes").jstree("get_checked", null, true).each
    (function () {
        divText.push($(this).children('a').text());
});

How to checkall, uncheckall, collapse and expand jsTree in MVC3 Razor project code is given below.

Comments/Suggestions are invited. Happy coding......!

Comments Post a Comment

Rahul 3/12/2013 (IST) / Reply

nice blog

Paul 5/14/2013 (IST) / Reply

How to pass the value of the selected node to the controller or on a text box in the same page?

sankar 5/25/2013 (IST) / Reply

Tree view

Jai 5/30/2013 (IST) / Reply

The download link for the Source code is not working, can you please provide the source code.

ceyhun 7/5/2013 (IST) / Reply

thanks very much. I tried to write this many weeks

Thilakshi 7/9/2013 (IST) / Reply

Thx for this code.It's working properly. Even though I wanna get check node Id as soon as when it's checked :(

Thilakshi 7/11/2013 (IST) / Reply

Unable to get parent nodes of selected child node

krishna 12/9/2013 (IST) / Reply

Working on jstree

son.tran 1/2/2014 (IST) / Reply

Run it affter download, i see function "Get ParentId and Text" return wrong value. Please help me!!

son.tran 1/3/2014 (IST) / Reply

How to get click child node event, and how to set event parameter? Please help me!!

nausheen 6/17/2014 (IST) / Reply

every thing is working.but when i try to implement on my project its not working :(

shn 10/14/2014 (IST) / Reply

afsdas

amuhaya 4/14/2015 (IST) / Reply

Good work

jeet 5/30/2015 (IST) / Reply

NoT GOOD BUT BAD

test 9/29/2015 (IST) / Reply

test

Raja 11/27/2015 (IST) / Reply

How to initially checked checkbox when load tree?

Siddharth vora 1/30/2016 (IST) / Reply

dfd

Arvind upadhyay 6/15/2016 (IST) / Reply

good working.....

Arvind upadhyay 6/23/2016 (IST) / Reply

how to checkbox show....