Lazy-loading TreeView with JsTree in Asp.Net MVC

mstfcck picture mstfcck · Aug 29, 2015 · Viewed 15.6k times · Source

I am using JsTree on my project. I want to do like that:

I want to show just root nodes when tree loaded first time after I want to show sub-nodes when I clicked root node (+) or of sub-node. I mean, I want to get from database and add to the sub-nodes when I clicked every node.

How can I do that in Asp.Net MVC? I looked almost every JsTree Ajax sample. But I couldn't do that. What should I return from action? How should I do my action Please help!

JsTree: https://www.jstree.com/

Samples:

Answer

mstfcck picture mstfcck · Sep 2, 2015

Finally, I found the problem!

I created a Model:

public class JsTreeModel
{
    public string id { get; set; }
    public string parent { get; set; } 
    public string text { get; set; }
    public bool children { get; set; } // if node has sub-nodes set true or not set false
}

I created a controller like following:

public class TreeviewController : Controller
{
    public JsonResult GetRoot()
    {
        List<JsTreeModel> items = GetTree();

        return new JsonResult { Data = items, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

    public JsonResult GetChildren(string id)
    {
        List<JsTreeModel> items = GetTree(id);

        return new JsonResult { Data = items, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

    static List<JsTreeModel> GetTree()
    {
        var items = new List<JsTreeModel>();

        // set items in here

        return items;
    }

    static List<JsTreeModel> GetTree(string id)
    {
        var items = new List<JsTreeModel>();

        // set items in here

        return items;
    }

}

Html:

<div id='treeview'></div>

Script:

$('#treeview').jstree({
    "plugins": ["search", "wholerow"],
    'core': {
        'data': {
            'url': function (node) {
                return node.id === '#' ? "/Treeview/GetRoot" : "/Treeview/GetChildren/" + node.id;

            },
            'data': function (node) {
                return { 'id': node.id };
            }
        }
    }
});

$('#treeview').on('changed.jstree', function (e, data) {
    console.log("=> selected node: " + data.node.id);
});