ASP.NET Core Blazor Component Virtualization in .NET 5 – An Overview
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (915)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (628)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (592)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
ASP.NET Core Blazor Component Virtualization in .NET 5 – An Overview

ASP.NET Core Blazor Component Virtualization in .NET 5 – An Overview

Virtualization is a technique that helps you to process and render only the items that are currently visible on the page (in the content viewport). We can use this technique when dealing with large amounts of data, where processing all the data and displaying the result will take time.

For example, if we want to display thousands of records in a table where the viewport can only hold 20 rows of data, we can use virtualization and process only the necessary data. Other data will be loaded and displayed dynamically when scrolling up or down.

Following are the prerequisites for implementing component virtualization:

Creating a Blazor WebAssembly application with .NET 5

Virtualization in a component can be implemented either in Blazor WebAssembly or Blazor Server applications. In this blog, we are going to implement virtualization in Blazor WebAssembly.

Follow these steps to create a Blazor WebAssembly application:

  1. Open Visual Studio 2019 and choose Create a new project.Choose Create a new project option from the list
  2. Type Blazor in the search window, select Blazor WebAssembly App from the list and click Next.
    Select Blazor WebAssembly App from the list and click Next
  3. Enter your project name and click Next. Here, I am choosing the name BlazorVirtualizationSample.
    Enter your project name and click Next
  4. Then, the Additional information dialog will open. In that, select .NET 5.0 as the target framework and click Create.
    Select .NET 5.0 as the target framework and click Create

The Blazor WebAssembly application will be created, as shown in the following screenshot.
Created Blazor WebAssembly project

Implementing virtualization

By default, the following three Razor pages will be included in the Blazor WebAssembly project:

  • Counter.razor
  • FetchData.razor
  • Index.razor

Now we are going to create a separate Razor page called Employee.razor and implement virtualization.

Employee.razor

@page "/employee"

<h2>Employee Details</h2>

@if (employees == null)
{
    <p><em>Loading Employees...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Employee Id</th>
                <th>Employee Name</th>
                <th>Role</th>
            </tr>
        </thead>
        <tbody>
            @*@foreach (var employee in employees)
                {
                    <tr>
                        <td>@employee.EmployeeId</td>
                        <td>@employee.Name</td>
                        <td>@employee.Role</td>
                    </tr>
                }*@

            <Virtualize Items="employees" Context="employee">
                <tr>
                    <td>@employee.EmployeeId</td>
                    <td>@employee.Name</td>
                    <td>@employee.Role</td>
                </tr>
            </Virtualize>
        </tbody>
    </table>
}

@code {
    private List<EmployeeDetails> employees;

    protected override async Task OnInitializedAsync()
    {
        employees = await GetEmployeeDetails();
    }

    private async Task<List<EmployeeDetails>> GetEmployeeDetails()
    {
        List<EmployeeDetails> employeeList = new List<EmployeeDetails>();
        List<string> roleList = new List<string>() { ".Net Developer", "Testing Engineer", "Graphic Designer", "Technical Writer", "Support Coordinator" };
        int roleArrayIndex = 0;
        int tempCount = 0;
        int employeeDataCount = 10000;

        for (int i = 1; i <= employeeDataCount; i++)
        {
            if (i > tempCount + employeeDataCount / roleList.Count())
            {
                roleArrayIndex++;
                tempCount = i - 1;
            }

            var employeeDetails = new EmployeeDetails()
            {
                EmployeeId = i,
                Name = "Employee " + i.ToString(),
                Role = roleList[roleArrayIndex]
            };

            employeeList.Add(employeeDetails);
        }
        return await Task.FromResult(employeeList);
    }

    public class EmployeeDetails
    {
        public int EmployeeId { get; set; }

        public string Name { get; set; }

        public string Role { get; set; }
    }

}

In Employee.razor, the GetEmployeeDetails() method returns 10,000 employee records with Employee ID, Name, and Role. Following are the few differences between the foreach section and Virtualize component.

In the classic approach of loading all the data during initial load, the application would take three to five seconds to load the page. Refer to the commented section of the code example.

@foreach (var employee in employees)
    {
        <tr>
            <td>@employee.EmployeeId</td>
            <td>@employee.Name</td>
            <td>@employee.Role</td>
        </tr>
    }

In the modern approach, when using virtualization, the application takes less than a second to display the initial data. Only the data that fits in the viewport is processed, so the time consumption is less than the classical approach.

<Virtualize Items="employees" Context="employee">
    <tr>
        <td>@employee.EmployeeId</td>
        <td>@employee.Name</td>
        <td>@employee.Role</td>
    </tr>
</Virtualize>

You can see in the following screenshot that only 23 rows of data were added to the table.
Blazor DataGrid with virtualization

However, on scrolling down, more data will be fetched and displayed on the table.

ItemsProvider

To take control of the number of items loaded in the table per request, use the ItemsProvider property of the Virtualize component. The ItemsProvider (delegate) asynchronously retrieves the requested items on demand (when scrolling down or up).

Add this method to @codeblock in the Employee.razor file.

private async ValueTask<ItemsProviderResult<EmployeeDetails>> LoadEmployeeDetails(ItemsProviderRequest request)
{
    var employees = await GetEmployeeDetails();
    return new ItemsProviderResult<EmployeeDetails>(employees.Skip(request.StartIndex).Take(request.Count), employees.Count());
}

When using ItemsProvider, no data will be loaded during the initialization time. But the Virtualize component will call the LoadEmployeeDetails method with the start index and request count (number of items to load) parameter on demand.

Also, the Virtualize component allows us to show a loading message using a place holder while data is loading.

<Virtualize ItemsProvider="LoadEmployeeDetails" Context="employee">
    <ItemContent>
        <tr>
            <td>@employee.EmployeeId</td>
            <td>@employee.Name</td>
            <td>@employee.Role</td>
        </tr>
    </ItemContent>
    <Placeholder>
        <p>Loading employee details...</p>
    </Placeholder>
</Virtualize>

Remove the following in the Employee.razor file. Instead, use a placeholder to display a loading message until the item data is available.

@if (employees == null)
{
    <p><em>Loading employee details...</em></p>
}

ItemSize

ItemSize is the size of an element in pixels and its default value is 50 pixels.

By default, the Virtualize component measures the rendering size (height) of individual items after the initial render occurs. Use ItemSize to provide an exact item size in advance to customize the size of each row and to ensure the correct scroll position for page reloads.

<Virtualize Items="employees" Context="employee" ItemSize="49">
    <tr>
        <td>@employee.EmployeeId</td>
        <td>@employee.Name</td>
        <td>@employee.Role</td>
    </tr> 
</Virtualize>

OverscanCount

OverscanCount determines the number of additional items rendered before and after the visible region as buffers. The default value of OverscanCount is three.

In the previous example, in the Virtualize implementation, we could see 23 data items on the page when we didn’t use the OverscanCount. If you want to load additional data items, customize the value of the OverscanCount. For example, if we set OverscanCount to 4, 24 data items load on the page.

Note: The default data item load count works based on the height of the container and the size of the rendered items. The data item load count might vary in different resolutions and zoom levels.

<Virtualize Items="employees" Context="employee" OverscanCount="4">
    <tr>
        <td>@employee.EmployeeId</td>
        <td>@employee.Name</td>
        <td>@employee.Role</td>
    </tr> 
</Virtualize>

Resources

For more information, refer to the Virtualize component in the Blazor demo.

Conclusion

Thank you for reading this article! In this article, we have clearly explained how to achieve virtualization in an ASP.NET Core Blazor WebAssembly application, using the Virtualize component available in .NET 5. We also have explained customizing the virtualization. I hope you found this article informative.

Essential Studio for Blazor offers the largest collection of components for the Blazor platform. It has popular components like ChartsDataGridSchedulerDiagramWord Processor, and Maps. It also includes unique file-format libraries for manipulating ExcelWordPDF, and PowerPoint files. Use them to build world-class applications!

Try our Blazor components by downloading a free 30-day trial, or check out our NuGet package. Feel free to peruse our online examples and documentation to explore other available features.

If you have questions, you can contact us through our feedback portalsupport forums, or Direct-Trac. We are always happy to assist you!

Reference: ASP.NET Core Blazor component virtualization

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed