OWASP O2 Platform Blog

Creating a jQuery jsTree using serialized JSON object

Based on the code samples from http://mohyuddin.blogspot.com/2009/05/binding-jstree-programmatically-with.html this O2 Platform script shows how to create a jsTree (jQuery plugin) using as a data source a serialized JSON object (this is perfect for use on a web service)

//var topPanel = panel.clear().add_Panel(); 
var topPanel = "Poc - jQuery jsTree".popupWindow(600,200);
 
var ie = topPanel.add_IE();                </pre>
&nbsp;

ie.showMessage("loading jstree js");

var jQuery = new IE_JQuery(ie);  

var cssFile = @"jquery.jstree.style.css".local();
var styleHtml =  "<style type=\"text/css\"> {0} </style>".format(cssFile.fileContents().remove("".line()));
var injectCSS = "$('body').append($('"  + styleHtml + "' ))";
ie.invokeEval(injectCSS);

//ie.invokeEval("<a href="http://static.jstree.com/v.1.0pre/jquery.jstree.js%22.uri().getHtml">http://static.jstree.com/v.1.0pre/jquery.jstree.js".uri().getHtml</a>());  // use to get jstree from jstree.com website
ie.invokeEval("jquery.jstree.js".local().fileContents());
jQuery.element("div").html("creating local tree");
ie.invokeEval("$('body').append($('<div id=\"testJsTree\"/>')); $('#testJsTree').html('test JsTree will go here');");

var jsTree = new JsTree();
jsTree.add_Node("node 1");
jsTree.add_Node("node 2") 
      .add_Node("child 1")
      .add_Nodes("sub child 1", "sub child 2");
jsTree.add_Nodes("node 3", "node 4");
 
ie.invokeEval("treeData = " + jsTree.jsonString());                                  // this creates a string for the serialized jsTree object
//ie.invokeEval("treeData = { 'data' : ['firstnode' ,'2ndNode', '3rdNode' ]  }");    // this creates a tree it manually
ie.invokeEval("jQuery('#testJsTree').jstree({ 'json_data' : treeData ,  'plugins' : [  'themes', 'json_data' , 'dnd']} );");

jQuery.element("div").html("tree created");

return "ok";
//O2File:JsTreeNode.cs
//O2File:IE_JQuery.cs
//O2Ref:WatiN.Core.1x.dll
//O2Ref:Microsoft.mshtml.dll

Here is the code of the JsTree class (in the JsTreeNode.cs file):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
//O2Ref:System.Web.Extensions.dll

namespace O2.XRules.Database.APIs
{
    public class JsTree
    {
        public List<JsTreeNode> data;
       
        public JsTree()
        {
            data = new List<JsTreeNode>();
        }
    }
   
    public class JsTreeNode
    {
        public Attributes attributes { get; set; }      
        public Data data  { get; set; }          
        public string state { get; set; }              
        public List<JsTreeNode> children { get; set; }          
       
        public JsTreeNode()
        {
            children = new  List<JsTreeNode>();
            data = new Data();
            attributes = new Attributes();
        }   
        public  JsTreeNode(string title) : this()
        {
            data.title = title;
        }
       
    }
    public class Attributes
    {
        public string id { get; set; }  
        public string rel { get; set; }          
        public string mdata { get; set; }      
    }
   
    public class Data
    {
        public string title { get; set; }      
        public string icon { get; set; }      
    }
   
    public static class JsTree_ExtensionMethods
    {
        public static string jsonString(this object _object)
        {
            return new JavaScriptSerializer().Serialize(_object);
        }
       
        public static JsTreeNode add_Node(this JsTree jsTree, string title)
        {
            var newJsTreeNode = new JsTreeNode(title);
            jsTree.data.Add(newJsTreeNode);
            return newJsTreeNode;
        }
       
        public static List<JsTreeNode> add_Nodes(this JsTree jsTree, params string[] titles)
        {
            var newJsTreeNodes = new List<JsTreeNode>();
            foreach(var title in titles)
                newJsTreeNodes.Add(jsTree.add_Node(title));
            return newJsTreeNodes;
        }
       
        public static JsTreeNode add_Node(this JsTreeNode jsTreeNode, string title)
        {
            var newJsTreeNode = new JsTreeNode(title);
            jsTreeNode.children.Add(newJsTreeNode);
            return newJsTreeNode;
        }
       
        public static List<JsTreeNode> add_Nodes(this JsTreeNode jsTreeNode, params string[] titles)
        {
            var newJsTreeNodes = new List<JsTreeNode>();
            foreach(var title in titles)
                newJsTreeNodes.Add(jsTreeNode.add_Node(title));
            return newJsTreeNodes;
        }
    }
}

Based on the original code sample, here is a working version of its test script:


List<JsTreeNode> nodesList = new List<JsTreeNode>();
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 = "close";

    node.children = new List<JsTreeNode>();

    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);
}
var jsTree = new JsTree();
jsTree.data= nodesList; 
var jsonData = new JavaScriptSerializer().Serialize(jsTree);       

return jsonData;   

June 21, 2011 - Posted by | IE Automation, jQuery, WatiN

3 Comments »

  1. Hey i am getting following error while running your code, could you please look into why i am getting error

    Invalid at the top level of the document. Error processing resource ‘http://localhost:60415/Default.aspx’. Line 1, Positio…

    {“data”:[{“attributes”:{“id”:”rootnod1″,”rel”:”folder”,”mdata”:”{draggable : false,max_children : 1, max_depth :1}”},”data”:…

    Comment by Samuel | December 23, 2011 | Reply

  2. Can you share more details about your code?

    Send a code sample to owasp-o2-platform@lists.owasp.org and I’ll reply there

    Actually, where are you getting your error? If that is in a browser, then I think that error is normal. What you get from this script is a JSON object which the browsers don’t know what to do with it (I.e. the idea is that you consume it from the jstree directly via AJAX)

    Comment by Dinis Cruz | January 13, 2012 | Reply

  3. This is a great article, I’ve done some work in a similar vein that may help someone – 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

    Thanks D.

    Comment by David Grover | March 8, 2012 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: