jsTree – Few examples with ASP.Net/C#

The examples below uses the latest jsTree build as obtained from jsTree. (The stable build – pre 1.0 fixed) I copied all the relevant folders and file under my scripts folder.

img1

The examples are developed using old WebForms.

Example 1:
Any html structured as nested ul->li can be easily transformed into a tree.

img2

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.6/jquery.min.js" type="text/javascript"></script>
<script src="Scripts/json2.min.js" type="text/javascript"></script>
<script src="Scripts/_lib/jquery.js" type="text/javascript"></script>
<script src="Scripts/jquery.jstree.js" language="javascript" type="text/javascript"></script>
<div id="demo1">
    <ul >
        <li><a>Categories</a>
            <ul>
                <li><a>Category 1</a>
                    <ul>
                        <li><a>Product A</a></li>
                        <li><a>Product B</a></li>
                        <li><a>Product C</a></li>
                    </ul>
                </li>
                <li><a>Category 2</a>
                    <ul>
                        <li><a>Product D</a></li>
                    </ul>
                </li>
            </ul>
        </li>
    </ul>
</div>
$(function () {
    $("#demo1").jstree({
        "plugins": ["themes", "html_data"]
    });
});

Example 2:
Tree using Checkbox.(html data and checkbox plugin)

img3

$(function () {
    $("#demo1").jstree({
        "plugins": ["themes", "html_data", 'checkbox', "types"]
    });
});

Example 3:
Tree with various bind/callbacks.

$(function () {
    $("#demo1").jstree({
        "plugins": ["themes", "html_data", 'checkbox', "types", "ui", "crrm"]
    })
.bind("select_node.jstree", function (e, data) {
    var CurrObj = data.rslt.obj;
    //Toggle on the click of that Node's name
    $("#demo1").jstree("toggle_node", data.rslt.obj);
})
.bind("hover_node.jstree", function (e, data) {
    //on hover
    var nodeId = data.rslt.obj[0].id;
})
.bind("loaded.jstree", function (event, data) {
    $(this).jstree("open_all");
    alert("tree loaded");
})
;
$("#OpenAllNode").click(function () {
//Open all nodes
    $("#demo1").jstree("open_all");
});

$("#CloseAllNode").click(function () {
//Close all nodes
    $("#demo1").jstree("close_all");
});

$("#btnRefresh").click(function () {
    //Will do a ajax call to refresh the tree
    $.jstree._reference($("#demo1")).refresh(-1);
});

Example 4:
Tree loaded with JSON data as obtained from server. Manually created the JSON data in codebehind. Later we’ll have this JSON created dynamically.

img4
The C# class representing each node.

public class G_JSTree
{
    public G_JsTreeAttribute attr;
    public G_JSTree[] children;
    public string data
    {
        get;
        set;
    }
    public int IdServerUse
    {
        get;
        set;
    }
    public string icons
    {
        get;
        set;
    }
    public string state
    {
        get;
        set;
    }
}

public class G_JsTreeAttribute
{
    public string id;
    public bool selected;
}

<script type="text/javascript">
$(document).ready(function () {
$("#demo1").jstree({
        "json_data": {
            "ajax": {
                "type": "POST",
                "dataType": "json",
                "contentType": "application/json;",
                "url": "JsTree-Json.aspx/GetAllNodes11",
                "data": function (node) {
                    return '{ "operation" : "get_children", "id" : 1 }';
                },
                "success": function (retval) {
                    return retval.d;
                }
            }
        },
        "plugins": ["themes", "json_data"]
    });
});
</script>

PageMethod

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static List<G_JSTree> GetAllNodes11(string id)
    {
        List<G_JSTree> G_JSTreeArray = new List<G_JSTree>();

        G_JSTree _G_JSTree = new G_JSTree();
        _G_JSTree.data = "x1";
        _G_JSTree.state = "closed";
        _G_JSTree.IdServerUse = 10;
        _G_JSTree.children = null;
        _G_JSTree.attr = new G_JsTreeAttribute { id = "10", selected = false };
        G_JSTreeArray.Add(_G_JSTree);

        G_JSTree _G_JSTree2 = new G_JSTree();
        var children =
            new G_JSTree[]
            {
                new G_JSTree { data = "x1-11", attr = new G_JsTreeAttribute { id = "201" } },
                new G_JSTree { data = "x1-12", attr = new G_JsTreeAttribute { id = "202" } },
                new G_JSTree { data = "x1-13", attr = new G_JsTreeAttribute { id = "203" } },
                new G_JSTree { data = "x1-14", attr = new G_JsTreeAttribute { id = "204" } },
            };
        _G_JSTree2.data = "x2";
        _G_JSTree2.IdServerUse = 20;
        _G_JSTree2.state = "closed";
        _G_JSTree2.children = children;
        _G_JSTree2.attr = new G_JsTreeAttribute { id = "20", selected = true };
        G_JSTreeArray.Add(_G_JSTree2);

        G_JSTree _G_JSTree3 = new G_JSTree();
        var children2 =
            new G_JSTree[]
            {
                new G_JSTree { data = "x2-11", attr = new G_JsTreeAttribute { id = "301" } },
                new G_JSTree { data = "x2-12", attr = new G_JsTreeAttribute { id = "302" }, children= new G_JSTree[]{new G_JSTree{data = "x2-21", attr = new G_JsTreeAttribute { id = "3011" }}} },
                new G_JSTree { data = "x2-13", attr = new G_JsTreeAttribute { id = "303" } },
                new G_JSTree { data = "x2-14", attr = new G_JsTreeAttribute { id = "304" } },
            };
        _G_JSTree3.data = "x3";
        _G_JSTree3.state = "closed";
        _G_JSTree3.IdServerUse = 30;
        _G_JSTree3.children = children2;
        _G_JSTree3.attr = new G_JsTreeAttribute { id = "30", selected = true };
        G_JSTreeArray.Add(_G_JSTree3);
        return G_JSTreeArray;
    }

Example 5:
The jsTree with async loading of the children.
With async loading, all chidren are not created during the initial load of jsTree. The children are loaded, on-demand, when user tries to open any particular node. However, if any node already has childen loaded, but not visible, then an AJAX trip to server is skipped. In the following example, if the state of a given node is closed and children not loaded yet, –> when user tries to open that node, an AJAX query, fetches all children for that node, dynamically from server.

img5       img6  img7

$("#demo1").jstree({
    "json_data": {
        "ajax": {
            "type": "POST",
            "dataType": "json",
            "async": true,
            "contentType": "application/json;",
            "opts": {
                "method": "POST",
                "url": "JsTree-JsonAsync.aspx/GetAllNodes11"
            },
            "url": "JsTree-JsonAsync.aspx/GetAllNodes11",
            "data": function (node) {
                if (node == -1) {
                    return '{ "operation" : "get_children", "id" : -1 }';
                }
                else {
                //get the children for this node
                 return '{ "operation" : "get_children", "id" : ' + $(node).attr("id") + ' }';
                }
            },
            "success": function (retval) {
                return retval.d;
            }
        }
    },
    "plugins": ["themes", "json_data"]
});
private static List<G_JSTree> AddChildNodes(int _ParentID, int NumOfChildren, string ParentName)
{
    List<G_JSTree> G_JSTreeArray = new List<G_JSTree>();
    int n = 10;
    for (int i = 0; i < NumOfChildren; i++)
    {
        int CurrChildId = (_ParentID == 0) ? n : ((_ParentID * 10) + i);
        G_JSTree _G_JSTree = new G_JSTree();
        _G_JSTree.data = (_ParentID == 0) ? "root" + "-Child" + i.ToString() : ParentName + CurrChildId.ToString() + i.ToString();
        _G_JSTree.state = "closed";  //For async to work
        _G_JSTree.IdServerUse = CurrChildId;
        _G_JSTree.children = null;
        _G_JSTree.attr = new G_JsTreeAttribute { id = CurrChildId.ToString(), selected = false };
        G_JSTreeArray.Add(_G_JSTree);
        n = n + 10;
    }
    return G_JSTreeArray;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<G_JSTree> GetAllNodes11(string id)
{
    if (id != "-1") //-1 means initial load else async loading of children
    {
        if (id == "10")
            //Add 3 children to parent node with id=10.
            return AddChildNodes(10, 3, "xxxx");
        else
            return new List<G_JSTree>();
    }
    List<G_JSTree> G_JSTreeArray = new List<G_JSTree>();

    //Creating the JsTree data
    //In live scenarios this will come from db or Web Service
    //Add 5 root nodes
    G_JSTreeArray.AddRange(AddChildNodes(0, 5, ""));

    //Add 4 children to 3rd root node
    //The third node has id=30
    //The child nodes will have ids like 301,302,303,304
    G_JSTreeArray[3].children = (AddChildNodes(30, 4, G_JSTreeArray[3].data)).ToArray();

    //Add 5 children to level1 Node at id=302
    G_JSTreeArray[3].children[1].children = (AddChildNodes(302, 4, G_JSTreeArray[3].children[1].data)).ToArray();
   
    return G_JSTreeArray;
}

Example 6:
Sync the jsTree with server. Basically passing the entire JSON from client end to server.
On server, the JSON is deserialized to corresponding c# class.

<div id="demo1">
</div>
<br />
<asp:button ID="Button1" runat="server" OnClientClick="a1(); return false;" text="Sync Tree" />

function a1() {
    var json1 = $("#demo1").jstree("json_data").get_json();
    var y1 = JSON.stringify(json1);
    $.ajax({
        type: "POST",
        url: "JsTree-SyncTree.aspx/SyncMyTree",  
        contentType: "application/json; charset=utf-8",   
        data: "{'MyTreeJson': '" + y1 + "'}",   
        dataType: "json",
        success: function (response) {
        }
    });
}

$(document).ready(function () {
    $("#demo1").jstree({
        "json_data": {
            "ajax": {
                "type": "POST",
                "dataType": "json",
                "contentType": "application/json;",
                "url": "JsTree-Json.aspx/GetAllNodes11",
                "data": function (node) {
                    return '{ "operation" : "get_children", "id" : 1 }';
                },
                "success": function (retval) {
                    return retval.d;
                }
            }
        },
        "plugins": ["themes", "json_data"]
    });
});

[WebMethod(EnableSession = true)]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static void SyncMyTree(string MyTreeJson)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        List<G_JSTree> G_JSTreeArray = ser.Deserialize<List<G_JSTree>>(MyTreeJson);
    }

Example 7:
Interactive jsTree with Add/Rename/Delete Node functionality.

img8

<script type="text/javascript">
    $(document).ready(function () {
        $("#demo1").jstree({
            "json_data": {
                "ajax": {
                    "type": "POST",
                    "dataType": "json",
                    "contentType": "application/json;",
                    "url": "JsTree-ContextMenu.aspx/GetAllNodes11",
                    "data": function (node) {
                        return '{ "operation" : "get_children", "id" : 1 }';
                    },
                    "success": function (retval) {
                        return retval.d;
                    }
                }
            },
            contextmenu: {
                items: function ($node) {
                    return {
                        createItem: {
                            "label": "Add Node",
                            "action": function (obj) { this.create(obj); alert(obj.text()) },
                            "_class": "class"
                        },
                        renameItem: {
                            "label": "Rename Node",
                            "action": function (obj) { this.rename(obj); }
                        },
                        deleteItem: {
                            "label": "Delete Node",
                            "action": function (obj) { this.remove(obj); }
                        }
                    };
                }
            },
            "plugins": ["themes", "json_data", "ui", "crrm", "contextmenu"]
        })
    .bind("rename.jstree", function (NODE, REF_NODE, event, data) {
        // You may run validation or fire an ajax to save it on server
        var nodeId = REF_NODE.rslt.obj[0].id;
        alert("Rename done: " + NODE.type);
        alert("Rename done: " + REF_NODE.rslt.new_name);
        alert("Rename done: " + REF_NODE.rslt.old_name);
        alert("Rename done: " + REF_NODE.rslt.obj[0].id);
        if (NODE.type === 'rename') {
            //Run Validation or
            //fire an ajax call to save the status on server
            //if validations fail rollback
            //$.jstree.rollback(data.rlbk);
            }

    });
    });
</script>
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<G_JSTree> GetAllNodes11(string id)
{
    List<G_JSTree> G_JSTreeArray = new List<G_JSTree>();

    G_JSTree _G_JSTree = new G_JSTree();
    _G_JSTree.data = "x1";
    _G_JSTree.state = "closed";
    _G_JSTree.IdServerUse = 10;
    _G_JSTree.children = null;
    _G_JSTree.attr = new G_JsTreeAttribute { id = "10", selected = false };
    G_JSTreeArray.Add(_G_JSTree);

    G_JSTree _G_JSTree2 = new G_JSTree();
    var children =
        new G_JSTree[]
        {
            new G_JSTree { data = "x1-11", attr = new G_JsTreeAttribute { id = "201" } },
            new G_JSTree { data = "x1-12", attr = new G_JsTreeAttribute { id = "202" } },
            new G_JSTree { data = "x1-13", attr = new G_JsTreeAttribute { id = "203" } },
            new G_JSTree { data = "x1-14", attr = new G_JsTreeAttribute { id = "204" } },
        };
    _G_JSTree2.data = "x2";
    _G_JSTree2.IdServerUse = 20;
    _G_JSTree2.state = "closed";
    _G_JSTree2.children = children;
    _G_JSTree2.attr = new G_JsTreeAttribute { id = "20", selected = true };
    G_JSTreeArray.Add(_G_JSTree2);

    G_JSTree _G_JSTree3 = new G_JSTree();
    var children2 =
        new G_JSTree[]
        {
            new G_JSTree { data = "x2-11", attr = new G_JsTreeAttribute { id = "301" } },
            new G_JSTree { data = "x2-12", attr = new G_JsTreeAttribute { id = "302" }, children= new G_JSTree[]{new G_JSTree{data = "x2-21", attr = new G_JsTreeAttribute { id = "3011" }}} },
            new G_JSTree { data = "x2-13", attr = new G_JsTreeAttribute { id = "303" } },
            new G_JSTree { data = "x2-14", attr = new G_JsTreeAttribute { id = "304" } },
        };
    _G_JSTree3.data = "x3";
    _G_JSTree3.state = "closed";
    _G_JSTree3.IdServerUse = 30;
    _G_JSTree3.children = children2;
    _G_JSTree3.attr = new G_JsTreeAttribute { id = "30", selected = true };
    G_JSTreeArray.Add(_G_JSTree3);
    return G_JSTreeArray;
}

That’s all for now. Thanks for reading.

This entry was posted in JQuery and tagged , , . Bookmark the permalink.

2 Responses to jsTree – Few examples with ASP.Net/C#

  1. Cristiano Martins says:

    $.jstree._reference($(“#demo1”)).refresh(-1); does not work in IE9
    :S :S :S
    You have other solution?

  2. Thulani says:

    Great examples! However, I notice a behaviour in example 4 where the first root X1 seems to add children in recursive fashion. According to definition that node does not have children.
    _G_JSTree.children = null; Will you please explain this behaviour or is it a bug in jsTree?

Leave a reply to Thulani Cancel reply