Virtual Mode
- 2 minutes to read
In addition to bound and unbound modes, the MVC TreeView can operate in a Virtual Mode, which significantly reduces a server’s load and start-up time when working with complex or dynamically generated hierarchies. In a Virtual Mode, data is retrieved on the server in chunks upon client requests. In essence, child nodes are not created and initialized until their parent node is expanded for the first time. This allows you to efficiently use server resources and avoid retrieving all hierarchical data for the TreeView.
The Virtual Mode is automatically activated if the TreeViewExtension.BindToVirtualData method is called. The method requires a delegate of the TreeViewVirtualModeCreateChildrenMethod type as a parameter that enables you to create a list of immediate child nodes for a particular node. Once assigned, this delegate method is called whenever a node is expanded for the first time. The processed node is passed as the method’s parameter. To indicate that a child node has no children, its TreeViewVirtualNode.IsLeaf property must be set 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";
}
}