Lazy-loading TreeView with JsTree in Asp.Net MVC

后端 未结 2 1695
你的背包
你的背包 2020-12-13 15:39

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 roo

2条回答
  •  心在旅途
    2020-12-13 16:37

    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:

    @* Content will be populated by jsTree *@

    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:

    After child node was clicked:

提交回复
热议问题