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.