Binding jsTree programmatically with server side entities using JSON in ASP.NET

jsTree is very useful jQuery based javascript component for displaying contents
in tree structure in hierarchical manner. In this small example I’ll give you a
demonstration how you can bind jsTree programmatically with sever side data using
JSON.
Before going for implementation first have a look on the format of JSON input
to create nodes.
json:  [   { attributes:  { id: "root1", rel: "root" }, 
        state: "open", data: "Root node 1", 
        children: [    { attributes: { id: "root1_child1", rel: "folder" }, 
         data: { title: "Custom icon", icon: "../images/ok.jpg" } 
      }, 
//.. . other nodes 
  ]

And here is the entity based implementation of a jsTree node.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class JsTreeNode
{
    public JsTreeNode()
    {
    }
    Attributes _attributes;
    public Attributes attributes
    {
        get
        {
            return _attributes;
        }
        set
        {
            _attributes = value;
        }
    }
    Data _data;
    public Data data
    {
        get
        {
            return _data;
        }
        set
        {
            _data = value;
        }
    }
    string _state;
    public string state
    {
        get
        {
            return _state;
        }
        set
        {
            _state = value;
        }
    }
    List _children;
    public List children
    {
        get
        {
            return _children;
        }
        set
        {
            _children = value;
        }
    }

}
public class Attributes
{
    string _id;

    public string id
    {
        get
        {
            return _id;
        }
        set
        {
            _id = value;
        }
    }
    string _rel;

    public string rel
    {
        get
        {
            return _rel;
        }
        set
        {
            _rel = value;
        }
    }
    string _mdata;

    public string mdata
    {
        get
        {
            return _mdata;
        }
        set
        {
            _mdata = value;
        }
    }
}

public class Data
{
    string _title;

    public string title
    {
        get
        {
            return _title;
        }
        set
        {
            _title = value;
        }
    }

    string _icon;

    public string icon
    {
        get
        {
            return _icon;
        }
        set
        {
            _icon = value;
        }
    }
}





As you can see the JSON , jsTree expects is collection nodes each having following
structure
{  attributes: { id: "pjson1_5", rel: "root2" },  data: "Root node 2" }

where state and children are optional fields to be set. Keeping the above anatomy
of jsTree node , we can creat server side class to have one-one mapping with these
json objects with composition/aggregation as  per needed so that we can bind
it with node collection populated from sever side. Lets create the main jsTreeNode
and other entities which compose its anatomy as shown above.
< The jsTreeNode is capable to fully map the jsTree json type node. And now its time to populate the jsTreeNode coollection bind the JsTree with it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            RouteCallbacks();
        }
    }
    void RouteCallbacks()
    {
        string callback = Request.Params["callback"];
        if (string.IsNullOrEmpty(callback))
            return;

        if (callback == "GetNodesJson")
            this.GetNodesJson();
    }
    void GetNodesJson()
    {
        List nodesList = new List();
        for (int i = 1; i < 10; i++)
        {
            JsTreeNode node = new JsTreeNode();
            node.attributes = new Attributes();
            node.attributes.id = "rootnod" + i;
            node.attributes.rel = "root" + i;
            node.data = new Data();
            node.data.title = "Root node:" + i;
            node.state = "open";

            node.children = new List();

            for (int j = 1; j < 4; j++)
            {
                JsTreeNode cnode = new JsTreeNode();
                cnode.attributes = new Attributes();
                cnode.attributes.id = "childnod1" + j;
                node.attributes.rel = "folder";
                cnode.data = new Data();
                cnode.data.title = "child node: " + j;
                cnode.attributes.mdata = "{draggable : true,max_children : 1,max_depth : 1 }";
                node.children.Add(cnode);

            }
            node.attributes.mdata = "{draggable : false,max_children : 1, max_depth :1}";
            nodesList.Add(node);
        }
        JavaScriptSerializer ser = new JavaScriptSerializer();
        string res = ser.Serialize(nodesList);
        Response.ContentType = "application/json";
        Response.Write(res);
        Response.End();
    }
}
 
Following is the client side complete code snipet required to bind jsTree with the server side entities based JSON data. Please dont forget to add jQuery and jsTree related js files reference to your page. The "rule{}" configuration is optional. It is only required if you want your jsTree to be all ***able.
<script type="text/javascript">
      $(function() {
            $("#divJsTreeDemo").tree({
            data: {
            type: "json",
            url: "Default.aspx?callback=GetNodesJson",
            async: true

            },

            rules: {
            metadata: "mdata",
            use_inline: true,
            clickable: ["root2", "folder"],
            deletable: "none",
            renameable: "all",
            creatable: ["folder"],
            draggable: ["folder"],
            dragrules: ["folder * folder", "folder inside root", "tree-drop inside root2"],
            drag_button: "left",
            droppable: ["tree-drop"]

            }
          });

      });

    </script>

Following is the page markup.
    <form id="form1" runat="server">
    <div id="divJsTreeDemo">
    </div>
    </form>

Here it is, Have a look. image Hope this helps. For more about jsTree please visit its website.

17 comments:

gattaca said...
This comment has been removed by the author.
gattaca said...

Could you send me the sample project file of Visual Studio?

I would use RestWCF to response a json string to a jstree...

gattaca88077@gmail.com

babuman said...

Thanks Mohyuddin. It is a good sample code. I followed your idea and created the necessary classes but unfortunately my jsTree does not show up. When the tree calls my WebService method, I can see that my method executes, creates and returns data. But after my Web method has finished, I still don't see any tree on the client. I know you can't comment on my question since I can't post my code. This post disallows HTML tags and also Server side Scripts. If there is a way of posting my code, please let me know.

Babu.

Mahr G. Mohyuddin said...

Hi Babu,

Please add onJSONdata callback to verify if you are getting JSON in response correctly. And use the following alertNode method to iterate it.

callback: {
onJSONdata : function(DATA,TREE_OBJ) {alertNode(DATA);
},


function alertNode(NODE) {
$.each(NODE,
function(key, value) {
alert(key +
" : " + value);
});

}

babuman said...

Thanks Mohyuddin. I will try your suggestion.

Babu.

Anonymous said...

Excelent Sample, but dont work for me

Please i need the code, dont work for me
luismj@gmail.com

Michal said...

Can I get a sample project on e-mail: michaltelega(at)interia.pl?

Thanks in advance

Anonymous said...

hi mahr,

I am trying to bind tree upto n level depth in that i am using recursive call can you guide me for that

José Eduardo said...

Hello Mahr
Can i get a sample with that project please?

mail: zecarro@gmail.com

Ty.

ZE said...

A lot of the examples/code in this sample no longer work - possibly this was written awhile back and since then the jstree has been revampled.Now everything is done using the plugins. This article should be updated.

dinis said...

Thanks for this code sample, with a couple modifications I was able to get it to work with the latest version of jQuery and jsTree.

Here is a blog post with details: http://mohyuddin.blogspot.com/2009/05/binding-jstree-programmatically-with.html

dinis said...

oops, used the wrong link above to the blog post with details of this working. Here is the correct oneL

http://o2platform.wordpress.com/2011/06/21/creating-a-jquery-jstree-using-serialized-json-object/

here is a variation using jQuery DataTable

http://o2platform.wordpress.com/2011/06/21/creating-a-jquery-datatable-using-serialized-json-object-2/

project code said...

hi Mohyuddin,
appreciate your work.......i implemented the same thing in a different way in spring framework by using json array and that is working fine also......but now i have one more requirement in which i have to add the node in my jstree from front end and along with i have to save the same in my DB along with parent id and child id......i got so may solution none of them is satisfied...

fahad said...

Hi Mohyuddin,

Appriciate your work. Can you send me the sample project to my email id panagarf@gmaildotcom.

Thanks and regards.

David Grover said...

Hi Mohyuddin,

This is exactly the right approach, I used a similar design to create a jsTree control at http://code.zyky.com/jsTreeView/Default.aspx and http://asp-net-elephant.blogspot.com/2012/01/how-to-use-jstree-in-aspnet-web-forms.html

Anonymous said...

asdfasdfasdf

Guest said...

Test

Post a Comment