Lazy-loading TreeView with JsTree in Asp.Net MVC

后端 未结 2 1691
你的背包
你的背包 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:31

    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 items = GetTree();
    
            return new JsonResult { Data = items, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    
        public JsonResult GetChildren(string id)
        {
            List items = GetTree(id);
    
            return new JsonResult { Data = items, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
    
        static List GetTree()
        {
            var items = new List();
    
            // set items in here
    
            return items;
        }
    
        static List GetTree(string id)
        {
            var items = new List();
    
            // set items in here
    
            return items;
        }
    
    }
    

    Html:

    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);
    });
    

提交回复
热议问题