Virtual Mode
- 2 minutes to read
In addition to bound and unbound modes, the MVC TreeView supports Virtual Mode. This mode significantly reduces server load and startup time for complex or dynamically generated hierarchies. In Virtual Mode, the extension retrieves data from the server in portions: at startup and when users expand nodes. Child nodes are created and initialized only when their parent node is expanded for the first time. This approach improves server resource usage and removes the need to load the entire hierarchy upfront.
Virtual Mode is enabled automatically when you call the TreeViewExtension.BindToVirtualData method. This method accepts a delegate of the TreeViewVirtualModeCreateChildrenMethod type that creates a list of immediate child nodes for a specific node. After assignment, the delegate is called whenever a node is expanded for the first time. The processed node is passed to the method as a parameter. To indicate that a child node has no children, set its TreeViewVirtualNode.IsLeaf property to true.
Note
The TreeViewSettings.SyncSelectionMode property affects the TreeView extension behavior in virtual mode.
- When the TreeViewSettings.SyncSelectionMode property is set to None, a delegate method, which was sent to the TreeViewExtension.BindToVirtualData method, is only called for the node being expanded.
- Otherwise, the delegate method is called for the node being expanded, and for all previously expanded nodes.
Examples
// Model (TreeViewVirtualModeHelper)
public class TreeViewVirtualModeHelper {
const string FileImageUrl = "~/Content/TreeView/FileSystem/file.png";
const string DirImageUrl = "~/Content/TreeView/FileSystem/directory.png";
static HttpRequest Request { get { return HttpContext.Current.Request; } }
public static void CreateChildren(TreeViewVirtualModeCreateChildrenEventArgs e) {
string parentNodePath = string.IsNullOrEmpty(e.NodeName) ? Request.MapPath("~/") : e.NodeName;
List<TreeViewVirtualNode> children = new List<TreeViewVirtualNode>();
if(Directory.Exists(parentNodePath)) {
foreach(string childPath in Directory.GetDirectories(parentNodePath)) {
string childDirName = Path.GetFileName(childPath);
if(IsSystemName(childDirName))
continue;
TreeViewVirtualNode childNode = new TreeViewVirtualNode(childPath, childDirName);
childNode.Image.Url = DirImageUrl;
children.Add(childNode);
}
foreach(string childPath in Directory.GetFiles(parentNodePath)) {
string childFileName = Path.GetFileName(childPath);
if(IsSystemName(childFileName))
continue;
TreeViewVirtualNode childNode = new TreeViewVirtualNode(childPath, childFileName);
childNode.IsLeaf = true;
childNode.Image.Url = FileImageUrl;
children.Add(childNode);
}
}
e.Children = children;
}
static bool IsSystemName(string name) {
name = name.ToLower();
return name.StartsWith("app_") || name == "bin" || name == "obj";
}
}