Virtualization in ASP.NET MVC Tree View

14 Sep 20264 minutes to read

The TreeView control supports UI virtualization to enhance performance when handling a large amount of data. This feature optimizes rendering by initially gathering all data but only rendering a subset of it during the initial load. The remaining items are then loaded dynamically as the user scrolls within the TreeView container.

To enable virtualization, set the enableVirtualization property to true and define a fixed height for the TreeView container.

In the following sample, the enableVirtualization property is enabled.

<div class="treecontainer">
    @Html.EJS().TreeView("tree").EnableVirtualization(true).ShowCheckBox(true).Height("400px").Fields(
        field => field.Id("Id")
                      .ParentID("PId")
                      .Text("Name")
                      .HasChildren("HasChild")
                      .Expanded("Expanded")
                      .DataSource(ViewBag.data)
    ).Render()
</div>

<style>
    .treecontainer {
        max-width: 500px;
        margin: 0 auto;
    }
</style>
using Syncfusion.EJ2.Navigations;
using System.Collections.Generic;
using System.Web.Mvc;

public class TreeViewController : Controller
{
    public ActionResult Virtualization()
    {
        List<TreeviewVirtualization> localData = new List<TreeviewVirtualization>();

        for (int i = 1; i <= 50; i++)
        {
            localData.Add(new TreeviewVirtualization
            {
                Id = i,
                Name = "Parent Node " + i,
                HasChild = true,
                Expanded = true
            });

            for (int j = 1; j <= 20; j++)
            {
                localData.Add(new TreeviewVirtualization
                {
                    Id = (i * 1000) + j,
                    PId = i,
                    Name = "Child Node " + i + "-" + j
                });
            }
        }

        ViewBag.data = localData;
        return View("~/Views/TreeView/Virtualization/Virtualization.cshtml");
    }
}

public class TreeviewVirtualization
{
    public int Id { get; set; }
    public int PId { get; set; }
    public string Name { get; set; }
    public bool HasChild { get; set; }
    public bool Expanded { get; set; }
}

Performance benefits

Virtualization provides the following performance benefits:

  • Reduced DOM elements: Only visible nodes are rendered in the DOM, reducing memory consumption.

  • Faster initial load: Large datasets load quickly as only a subset of nodes are rendered initially.

  • Smooth scrolling: Dynamic loading ensures smooth scrolling experience without lag.

  • Lower CPU usage: Rendering fewer elements reduces CPU consumption.

Important notes

  • The height property is required when virtualization is enabled.