在Asp.Net MVC中使用JsTree延迟加载TreeView
我在我的项目中使用JsTree。 我想这样做:
我想在单击根节点(+)或子节点时显示子节点后第一次加载树时,只显示根节点。 我的意思是,当我点击每个节点时,我想从数据库中获取并添加到子节点。
我怎么能在Asp.Net MVC中做到这一点? 我查看了几乎每个JsTree Ajax示例。 但我做不到。 我该怎么回事呢? 我该怎么做我的行动请帮忙!
JsTree: https ://www.jstree.com/
样品:
- jsTree – 根据需要通过ajax加载子节点
- jsTree:动态附加子节点
- JSTree – 动态加载节点
最后,我发现了问题!
我创建了一个模型:
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 }
我创建了一个如下控制器:
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:
仅使用一个操作方法和延迟加载节点的示例。 以防万一有人需要在Asp.Net Mvc中使用jsTree 。
cshtml查看:
@* Content will be populated by jsTree *@
C#,’对象’控制器:
[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 }; }
第一次通话后:
单击子节点后: