Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy-loading TreeView with JsTree in Asp.Net MVC

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:

  • jsTree - loading subnodes via ajax on demand
  • jsTree : Append child node dynamically
  • JSTree - Load nodes dynamically
like image 289
mstfcck Avatar asked Aug 29 '15 20:08

mstfcck


2 Answers

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);
});
like image 61
mstfcck Avatar answered Nov 12 '22 02:11

mstfcck


Example with just one action method and lazy loading nodes. Just in case that someone needs to use jsTree with Asp.Net Mvc.

cshtml View:

<div data-key="@Model.Key" id="object-children-tree">
    @* Content will be populated by jsTree *@
</div>

<script type="text/javascript">
    $(function() {
        var $children = $("#object-children-tree");

        $children.jstree({
            "core": {
                "animation": 0,
                "data": {
                    "url": function(node) {
                        return '@Url.Action("GetChildren", "Object")';
                    },
                    "data": function (node) {
                        // Each time jstree needs to make an AJAX call this function will be called.
                        // It adds 'key' and 'isRoot' as parameter to ajax call. See signature of 'GetChildren' method.
                        // # is the special ID that the function receives when jstree needs to load the root nodes.
                        var isRoot = false;
                        var key = node.id;
                        if (key === "#") {
                            isRoot = true;
                            key = $("#object-children-tree").data("key");
                        }
                        return { "key": key, "isRoot": isRoot };
                    }
                }
            },
            "plugins": ["wholerow"]
        });
    });
</script>

C#, 'Object' controller:

[HttpGet]
public JsonResult GetChildren(string key, bool isRoot)
{
    // Populates the tree using AJAX and lazy loading nodes.
    // Lazy loading makes it possible to load nodes on the fly.
    // jstree will perform AJAX requests as the user browses the tree.
    //  
    // children = true, this special value indicated to jstree, that it has to lazy load the child node node.
    // https://github.com/vakata/jstree#populating-the-tree-using-ajax

    if (isRoot)
    {
        var first = new[]
        {
            new
            {
                id = "root-id",
                text = "Selected object in the list",
                state = new
                {
                    opened = true,
                },
                children = new[]
                {
                    new
                    {
                        id = "child-1",
                        text = "Child 1",
                        children = true
                    },
                    new
                    {
                        id = "child-2",
                        text = "Child 2",
                        children = true
                    }
                }
            }
        }
        .ToList(); 

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

    var g1 = Guid.NewGuid().ToString();
    var g2 = Guid.NewGuid().ToString();
    var next = new[]
    {
        new
        {
            id = "child-" + g1,
            text = "Child " + g1,
            children = true
        },
        new {
            id = "child-" + g2,
            text = "Child " + g2,
            children = true
        }
    }
    .ToList();

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

After first call:

enter image description here

After child node was clicked:

enter image description here

like image 5
Daniel Dušek Avatar answered Nov 12 '22 00:11

Daniel Dušek