Sample Code for jstree Ajax Call and Search


Completed guide for setup jstree ajax ,search by ajax, Lazy Loading on jstree when heavy node on your tree.

Server Side Script


public class TreeState
   {    
 
       public bool loaded { setget; }
       public bool opened { setget; }
       public bool selected { setget; }
       public bool disbled { setget; }
   }

public class TreeNode
   {
       public TreeNode()
       {
       }
 
       public TreeNode(string text)
       {
           this.text = text;
       }
 
       public TreeNode(string text, string icon)
       {
           this.text = text;
           this.icon = icon;
       }
 
 
       public string id { setget; }
       public string parent { setget; }
       public bool children { setget; }
       public string text { getset; }
       public string icon { getset; }
       public TreeState state { setget; }
       public string type { setget; }
       public string style { setget; }
       public object NodeObject { setget; }
   }

[HttpPost]
public JsonResult GetTreeNode(Dictionary<string,string> search)
{           
    List<TreeNode> tree = new List<TreeNode>();
    tree.Add(new TreeNode() {id="1",text="",state=new TreeState() { } });
    if(search.ContainsKey("str"))
    {
        //Do your search by name here
        //Format return is List<string> of all Id include with parent id
        //Please make sure the parent id is exist
        //Format ["idA","idAChild1","idAChild2","idAChild2Child1"]
        return Json(tree.Select(x=> x.id).ToList());     } else if(search.ContainsKey("Parentid"))     {         // do your search server side here         //Format is List<TreeNode>         return Json(tree);     }    }
Client Side Script jstree
var url ="/controllerName/GetTreeNode";
$("#treenode").jstree({
       "core": {
           "data": {
               "url": url,
               "type":"post",
               "data"function (node) {
                   return { "ParentId": node.id };
               }
           }
       },
       "search": {        
           "show_only_matches"true,
           ajax: {
               "url": url,
               "type""post",
               "data"function (str) {
                   return { "str": str };
 
               }        
           }
       },
       "plugins": ["search"],
   });
   var searching = false;
   $('#datasearch').keyup(function () {
 
       if (!searching) {
           searching = true;
           setTimeout(function () {
               searching = false;
               var v = $('#datasearch').val();
               $("#treenode").jstree(true).search(v);         
        
            }, 1000);
       }
 
   });

Comments

Popular posts from this blog

Key Value pair html UI with select 2 integration