The common process when using the TreeView is to bind to a collection of items. However, in some cases, you would want to delay the loading of a nodes child items until they are actually needed. This method is especially useful if you have a very deep tree, with lots of levels and child nodes and a simple example of this, is the folder structure of your Windows computer.
The TreeView control makes lazy loading easy to implement. To display TreeView in lazy loading mode, define an action to load the items when required and set the action URL to the lazy-load-action-url tag in case of tag helpers. In HTML helpers, you need to use the Bind property which uses a second parameter for action that returns lazy loading data.
Apart from this, you can also set lazy loading at client-side using JavaScript code. Set the LazyLoadFunction property to a function name, which invokes when a user expands the node. This function takes two parameters; the parent node and a callback to be invoked when the data becomes available.
The example code below helps you to understand the implementation of lazy loading feature in the TreeView control.
Model - EmployeeEx.cs
C# |
Copy Code
|
---|---|
using System.Collections.Generic; using System.Linq; using System.Data.Entity; namespace LazyLoading.Models { public class EmployeeEx { private static DbSet employees = new C1NWindEntities().Employees; public int EmployeeID { get; set; } public string Name { get; set; } public EmployeeEx[] SubExployees { get; set; } public static IEnumerable GetEmployees(int? leaderID) { return employees.Where(e => e.ReportsTo == leaderID).ToList().Select(e => new EmployeeEx { EmployeeID = e.EmployeeID, Name = e.FirstName + " " + e.LastName, SubExployees = employees.Any(ep => ep.ReportsTo == e.EmployeeID) ? new EmployeeEx[0] : null }); } } } |
Controller - LazyLoadingController.cs
Razor |
Copy Code
|
---|---|
using C1.Web.Mvc; using System.Web.Mvc; using <ApplicationName.Models>; namespace LazyLoading.Controllers { partial class TreeViewController : Controller { // GET: LazyLoad public ActionResult LazyLoading() { return View(); } public ActionResult Load() { return Json(EmployeeEx.GetEmployees(null)); } public ActionResult LazyLoading_LoadAction([C1JsonRequest]TreeNode node) { var leaderID = (int?)node.DataItem["EmployeeID"]; return Json(EmployeeEx.GetEmployees(leaderID)); } } } |
View - LazyLoading.cshtml
Razor |
Copy Code
|
---|---|
@(Html.C1().TreeView() .Bind(Url.Action("Load"), Url.Action("LazyLoading_LoadAction")) .DisplayMemberPath("Name") .ChildItemsPath("SubExployees")) |