ASP.NET Core Blazor QuickGrid
component
The QuickGrid
component is a Razor component for quickly and efficiently displaying data in tabular form. QuickGrid
provides a simple and convenient data grid component for common grid rendering scenarios and serves as a reference architecture and performance baseline for building data grid components. QuickGrid
is highly optimized and uses advanced techniques to achieve optimal rendering performance.
Package
Add a package reference for the Microsoft.AspNetCore.Components.QuickGrid
package.
Note
For guidance on adding packages to .NET apps, see the articles under Install and manage packages at Package consumption workflow (NuGet documentation). Confirm correct package versions at NuGet.org.
Sample app
For various QuickGrid
demonstrations, see the QuickGrid for Blazor sample app. The demo site is hosted on GitHub Pages. The site loads fast thanks to static prerendering using the community-maintained BlazorWasmPrerendering.Build
GitHub project.
QuickGrid
implementation
To implement a QuickGrid
component:
- Specify tags for the
QuickGrid
component in Razor markup (<QuickGrid>...</QuickGrid>
). - Name a queryable source of data for the grid. Use either of the following data sources:
- Items: A nullable
IQueryable<TGridItem>
, whereTGridItem
is the type of data represented by each row in the grid. - ItemsProvider: A callback that supplies data for the grid.
- Items: A nullable
- Class: An optional CSS class name. If provided, the class name is included in the
class
attribute of the rendered table. - Theme: A theme name (default value:
default
). This affects which styling rules match the table. - Virtualize: If true, the grid is rendered with virtualization. This is normally used in conjunction with scrolling and causes the grid to fetch and render only the data around the current scroll viewport. This can greatly improve the performance when scrolling through large data sets. If you use Virtualize, you should supply a value for ItemSize and must ensure that every row renders with a constant height. Generally, it's preferable not to use Virtualize if the amount of data rendered is small or if you're using pagination.
- ItemSize: Only applicable when using Virtualize. ItemSize defines an expected height in pixels for each row, allowing the virtualization mechanism to fetch the correct number of items to match the display size and to ensure accurate scrolling.
- ItemKey: Optionally defines a value for
@key
on each rendered row. Typically, this is used to specify a unique identifier, such as a primary key value, for each data item. This allows the grid to preserve the association between row elements and data items based on their unique identifiers, even when theTGridItem
instances are replaced by new copies (for example, after a new query against the underlying data store). If not set, the@key
is theTGridItem
instance. OverscanCount
: Defines how many additional items to render before and after the visible region to reduce rendering frequency during scrolling. While higher values can improve scroll smoothness by rendering more items off-screen, a higher value can also result in an increase in initial load times. Finding a balance based on your data set size and user experience requirements is recommended. The default value is 3. Only available when using Virtualize.- Pagination: Optionally links this
TGridItem
instance with a PaginationState model, causing the grid to fetch and render only the current page of data. This is normally used in conjunction with a Paginator component or some other UI logic that displays and updates the supplied PaginationState instance. - In the
QuickGrid
child content (RenderFragment), specify PropertyColumn<TGridItem,TProp>s, which representTGridItem
columns whose cells display values:- Property: Defines the value to be displayed in this column's cells.
- Format: Optionally specifies a format string for the value. Using Format requires the
TProp
type to implement IFormattable. - Sortable: Indicates whether the data should be sortable by this column. The default value may vary according to the column type. For example, a TemplateColumn<TGridItem> is sortable by default if any SortBy parameter is specified.
- InitialSortDirection: Indicates the sort direction if IsDefaultSortColumn is
true
. - IsDefaultSortColumn: Indicates whether this column should be sorted by default.
- PlaceholderTemplate: If specified, virtualized grids use this template to render cells whose data hasn't been loaded.
- HeaderTemplate: An optional template for this column's header cell. If not specified, the default header template includes the Title, along with any applicable sort indicators and options buttons.
- Title: Title text for the column. The title is rendered automatically if HeaderTemplate isn't used.
- Specify tags for the
QuickGrid
component in Razor markup (<QuickGrid>...</QuickGrid>
). - Name a queryable source of data for the grid. Use either of the following data sources:
- Items: A nullable
IQueryable<TGridItem>
, whereTGridItem
is the type of data represented by each row in the grid. - ItemsProvider: A callback that supplies data for the grid.
- Items: A nullable
- Class: An optional CSS class name. If provided, the class name is included in the
class
attribute of the rendered table. - Theme: A theme name (default value:
default
). This affects which styling rules match the table. - Virtualize: If true, the grid is rendered with virtualization. This is normally used in conjunction with scrolling and causes the grid to fetch and render only the data around the current scroll viewport. This can greatly improve the performance when scrolling through large data sets. If you use Virtualize, you should supply a value for ItemSize and must ensure that every row renders with a constant height. Generally, it's preferable not to use Virtualize if the amount of data rendered is small or if you're using pagination.
- ItemSize: Only applicable when using Virtualize. ItemSize defines an expected height in pixels for each row, allowing the virtualization mechanism to fetch the correct number of items to match the display size and to ensure accurate scrolling.
- ItemKey: Optionally defines a value for
@key
on each rendered row. Typically, this is used to specify a unique identifier, such as a primary key value, for each data item. This allows the grid to preserve the association between row elements and data items based on their unique identifiers, even when theTGridItem
instances are replaced by new copies (for example, after a new query against the underlying data store). If not set, the@key
is theTGridItem
instance. - Pagination: Optionally links this
TGridItem
instance with a PaginationState model, causing the grid to fetch and render only the current page of data. This is normally used in conjunction with a Paginator component or some other UI logic that displays and updates the supplied PaginationState instance. - In the
QuickGrid
child content (RenderFragment), specify PropertyColumn<TGridItem,TProp>s, which representTGridItem
columns whose cells display values:- Property: Defines the value to be displayed in this column's cells.
- Format: Optionally specifies a format string for the value. Using Format requires the
TProp
type to implement IFormattable. - Sortable: Indicates whether the data should be sortable by this column. The default value may vary according to the column type. For example, a TemplateColumn<TGridItem> is sortable by default if any SortBy parameter is specified.
- InitialSortDirection: Indicates the sort direction if IsDefaultSortColumn is
true
. - IsDefaultSortColumn: Indicates whether this column should be sorted by default.
- PlaceholderTemplate: If specified, virtualized grids use this template to render cells whose data hasn't been loaded.
- HeaderTemplate: An optional template for this column's header cell. If not specified, the default header template includes the Title, along with any applicable sort indicators and options buttons.
- Title: Title text for the column. The title is rendered automatically if HeaderTemplate isn't used.
For example, add the following component to render a grid.
For Blazor Web Apps, the QuickGrid
component must adopt an interactive render mode to enable interactive features, such as paging and sorting.
PromotionGrid.razor
:
@page "/promotion-grid"
@using Microsoft.AspNetCore.Components.QuickGrid
<PageTitle>Promotion Grid</PageTitle>
<h1>Promotion Grid Example</h1>
<QuickGrid Items="people">
<PropertyColumn Property="@(p => p.PersonId)" Sortable="true" />
<PropertyColumn Property="@(p => p.Name)" Sortable="true" />
<PropertyColumn Property="@(p => p.PromotionDate)" Format="yyyy-MM-dd" Sortable="true" />
</QuickGrid>
@code {
private record Person(int PersonId, string Name, DateOnly PromotionDate);
private IQueryable<Person> people = new[]
{
new Person(10895, "Jean Martin", new DateOnly(1985, 3, 16)),
new Person(10944, "António Langa", new DateOnly(1991, 12, 1)),
new Person(11203, "Julie Smith", new DateOnly(1958, 10, 10)),
new Person(11205, "Nur Sari", new DateOnly(1922, 4, 27)),
new Person(11898, "Jose Hernandez", new DateOnly(2011, 5, 3)),
new Person(12130, "Kenji Sato", new DateOnly(2004, 1, 9)),
}.AsQueryable();
}
Access the component in a browser at the relative path /promotion-grid
.
There aren't current plans to extend QuickGrid
with features that full-blown commercial grids tend to offer, for example, hierarchical rows, drag-to-reorder columns, or Excel-like range selections. If you require advanced features that you don't wish to develop on your own, continue using third-party grids.
Sort by column
The QuickGrid
component can sort items by columns. In Blazor Web Apps, sorting requires the component to adopt an interactive render mode.
Add Sortable="true"
(Sortable) to the PropertyColumn<TGridItem,TProp> tag:
<PropertyColumn Property="..." Sortable="true" />
In the running app, sort the QuickGrid
column by selecting the rendered column title.
Page items with a Paginator
component
The QuickGrid
component can page data from the data source. In Blazor Web Apps, paging requires the component to adopt an interactive render mode.
Add a PaginationState instance to the component's @code
block. Set the ItemsPerPage to the number of items to display per page. In the following example, the instance is named pagination
, and ten items per page is set:
PaginationState pagination = new PaginationState { ItemsPerPage = 10 };
Set the QuickGrid
component's Pagination property to pagination
:
<QuickGrid Items="..." Pagination="pagination">
To provide a UI for pagination, add a Paginator
component above or below the QuickGrid
component. Set the Paginator.State to pagination
:
<Paginator State="pagination" />
In the running app, page through the items using a rendered Paginator
component.
Custom attributes and styles
QuickGrid also supports passing custom attributes and style classes (Class) to the rendered table element:
<QuickGrid Items="..." custom-attribute="value" Class="custom-class">
Entity Framework Core (EF Core) data source
Use the factory pattern to resolve an EF Core database context that provides data to a QuickGrid
component. For more information on why the factory pattern is recommended, see ASP.NET Core Blazor with Entity Framework Core (EF Core).
A database context factory (IDbContextFactory<TContext>) is injected into the component with the @inject
directive. The factory approach requires disposal of the database context, so the component implements the IAsyncDisposable interface with the @implements
directive. The item provider for the QuickGrid
component is a DbSet<T>
obtained from the created database context (CreateDbContext) of the injected database context factory.
QuickGrid recognizes EF-supplied IQueryable instances and knows how to resolve queries asynchronously for efficiency.
Add a package reference for the Microsoft.AspNetCore.Components.QuickGrid.EntityFrameworkAdapter
NuGet package.
Note
For guidance on adding packages to .NET apps, see the articles under Install and manage packages at Package consumption workflow (NuGet documentation). Confirm correct package versions at NuGet.org.
Call AddQuickGridEntityFrameworkAdapter on the service collection in the Program
file to register an EF-aware IAsyncQueryExecutor implementation:
builder.Services.AddQuickGridEntityFrameworkAdapter();
The following example uses an ExampleTable
DbSet<TEntity> (table) from a AppDbContext
database context (context
) as the data source for a QuickGrid
component:
@using Microsoft.AspNetCore.Components.QuickGrid
@using Microsoft.EntityFrameworkCore
@implements IAsyncDisposable
@inject IDbContextFactory<AppDbContext> DbFactory
...
<QuickGrid ... Items="context.ExampleTable" ...>
...
</QuickGrid>
@code {
private AppDbContext context = default!;
protected override void OnInitialized()
{
context = DbFactory.CreateDbContext();
}
public async ValueTask DisposeAsync() => await context.DisposeAsync();
}
In the code block (@code
) of the preceding example:
- The
context
field holds the database context, typed as anAppDbContext
. - The
OnInitialized
lifecycle method assigns a new database context (CreateDbContext) to thecontext
field from the injected factory (DbFactory
). - The asynchronous
DisposeAsync
method disposes of the database context when the component is disposed.
You may also use any EF-supported LINQ operator to filter the data before passing it to the Items parameter.
The following example filters movies by a movie title entered in a search box. The database context is BlazorWebAppMoviesContext
, and the model is Movie
. The movie's Title
property is used for the filter operation.
@using Microsoft.AspNetCore.Components.QuickGrid
@using Microsoft.EntityFrameworkCore
@implements IAsyncDisposable
@inject IDbContextFactory<BlazorWebAppMoviesContext> DbFactory
...
<p>
<input type="search" @bind="titleFilter" @bind:event="oninput" />
</p>
<QuickGrid ... Items="FilteredMovies" ...>
...
</QuickGrid>
@code {
private string titleFilter = string.Empty;
private BlazorWebAppMoviesContext context = default!;
protected override void OnInitialized()
{
context = DbFactory.CreateDbContext();
}
private IQueryable<Movie> FilteredMovies =>
context.Movie.Where(m => m.Title!.Contains(titleFilter));
public async ValueTask DisposeAsync() => await context.DisposeAsync();
}
Display name support
A column title can be assigned using ColumnBase<TGridItem>.Title in the PropertyColumn<TGridItem,TProp>'s tag. In the following movie example, the column is given the name "Release Date
" for the column's movie release date data:
<PropertyColumn Property="movie => movie.ReleaseDate" Title="Release Date" />
However, managing column titles (names) from bound model properties is usually a better choice for maintaining an app. A model can control the display name of a property with the [Display]
attribute. In the following example, the model specifies a movie release date display name of "Release Date
" for its ReleaseDate
property:
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
To enable the QuickGrid
component to use the DisplayAttribute.Name, subclass PropertyColumn<TGridItem,TProp> either in the component or in a separate class:
public class DisplayNameColumn<TGridItem, TProp> : PropertyColumn<TGridItem, TProp>
{
protected override void OnParametersSet()
{
if (Title is null && Property.Body is MemberExpression memberExpression)
{
var memberInfo = memberExpression.Member;
Title =
memberInfo.GetCustomAttribute<DisplayNameAttribute>().DisplayName ??
memberInfo.GetCustomAttribute<DisplayAttribute>().Name ??
memberInfo.Name;
}
base.OnParametersSet();
}
}
Use the subclass in the QuickGrid
component. In the following example, the preceding DisplayNameColumn
is used. The name "Release Date
" is provided by the [Display]
attribute in the model, so there's no need to specify a Title:
<DisplayNameColumn Property="movie => movie.ReleaseDate" />
The [DisplayName]
attribute is also supported:
[DisplayName("Release Date")]
public DateTime ReleaseDate { get; set; }
However, the [Display]
attribute is recommended because it makes additional properties available. For example, the [Display]
attribute offers the ability to assign a resource type for localization.
Remote data
In Blazor WebAssembly apps, fetching data from a JSON-based web API on a server is a common requirement. To fetch only the data that's required for the current page/viewport of data and apply sorting or filtering rules on the server, use the ItemsProvider parameter.
ItemsProvider can also be used in a server-side Blazor app if the app is required to query an external endpoint or in other cases where the requirements aren't covered by an IQueryable.
Supply a callback matching the GridItemsProvider<TGridItem> delegate type, where TGridItem
is the type of data displayed in the grid. The callback is given a parameter of type GridItemsProviderRequest<TGridItem>, which specifies the start index, maximum row count, and sort order of data to return. In addition to returning the matching items, a total item count (totalItemCount
) is also required for paging and virtualization to function correctly.
The following example obtains data from the public OpenFDA Food Enforcement database.
The GridItemsProvider<TGridItem> converts the GridItemsProviderRequest<TGridItem> into a query against the OpenFDA database. Query parameters are translated into the particular URL format supported by the external JSON API. It's only possible to perform sorting and filtering via sorting and filtering that's supported by the external API. The OpenFDA endpoint doesn't support sorting, so none of the columns are marked as sortable. However, it does support skipping records (skip
parameter) and limiting the return of records (limit
parameter), so the component can enable virtualization and scroll quickly through tens of thousands of records.
FoodRecalls.razor
:
@page "/food-recalls"
@inject HttpClient Http
@inject NavigationManager NavManager
<PageTitle>Food Recalls</PageTitle>
<h1>OpenFDA Food Recalls</h1>
<div class="grid" tabindex="-1">
<QuickGrid ItemsProvider="@foodRecallProvider" Virtualize="true">
<PropertyColumn Title="ID" Property="@(c => c.Event_Id)" />
<PropertyColumn Property="@(c => c.State)" />
<PropertyColumn Property="@(c => c.City)" />
<PropertyColumn Title="Company" Property="@(c => c.Recalling_Firm)" />
<PropertyColumn Property="@(c => c.Status)" />
</QuickGrid>
</div>
<p>Total: <strong>@numResults results found</strong></p>
@code {
GridItemsProvider<FoodRecall>? foodRecallProvider;
int numResults;
protected override async Task OnInitializedAsync()
{
foodRecallProvider = async req =>
{
var url = NavManager.GetUriWithQueryParameters(
"https://api.fda.gov/food/enforcement.json",
new Dictionary<string, object?>
{
{ "skip", req.StartIndex },
{ "limit", req.Count },
});
var response = await Http.GetFromJsonAsync<FoodRecallQueryResult>(
url, req.CancellationToken);
return GridItemsProviderResult.From(
items: response!.Results,
totalItemCount: response!.Meta.Results.Total);
};
numResults = (await Http.GetFromJsonAsync<FoodRecallQueryResult>(
"https://api.fda.gov/food/enforcement.json"))!.Meta.Results.Total;
}
}
For more information on calling web APIs, see Call a web API from an ASP.NET Core Blazor app.
QuickGrid
scaffolder
The QuickGrid
scaffolder scaffolds Razor components with QuickGrid
to display data from a database.
The scaffolder generates basic Create, Read, Update, and Delete (CRUD) pages based on an Entity Framework Core data model. You can scaffold individual pages or all of the CRUD pages. You select the model class and the DbContext
, optionally creating a new DbContext
if needed.
The scaffolded Razor components are added to the project's in a generated folder named after the model class. The generated Index
component uses a QuickGrid
component to display the data. Customize the generated components as needed and enable interactivity to take advantage of interactive features, such as paging, sorting and filtering.
The components produced by the scaffolder require server-side rendering (SSR), so they aren't supported when running on WebAssembly.
Right-click on the Components/Pages
folder and select Add > New Scaffolded Item.
With the Add New Scaffold Item dialog open to Installed > Common > Razor Component, select Razor Components using Entity Framework (CRUD). Select the Add button.
Complete the Add Razor Components using Entity Framework (CRUD) dialog:
- The Template dropdown list includes other templates for specifically creating create, edit, delete, details, and list components. This dropdown list comes in handy when you only need to create a specific type of component scaffolded to a model class. Leave the Template dropdown list set to CRUD to scaffold a full set of components.
- In the Model class dropdown list, select the model class. A folder is created for the generated components from the model name (if the model class is named
Movie
, the folder is automatically namedMoviePages
). - For DbContext class, select an existing database context or select the + (plus sign) button and Add Data Context modal dialog to add a new database context.
- After the model dialog closes, the Database provider dropdown list defaults to SQL Server. You can select the appropriate provider for the database that you're using. The options include SQL Server, SQLite, PostgreSQL, and Azure Cosmos DB.
- Select Add.
ASP.NET Core