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 { set; get; }
public bool opened { set; get; }
public bool selected { set; get; }
public bool disbled { set; get; }
}
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 { set; get; }
public string parent { set; get; }
public bool children { set; get; }
public string text { get; set; }
public string icon { get; set; }
public TreeState state { set; get; }
public string type { set; get; }
public string style { set; get; }
public object NodeObject { set; get; }
}
[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
Post a Comment