Data Table
This is an in-depth guide on how to use the NvDatatable component, covering column configuration, custom cell rendering, pagination modes, and best practices. For API documentation and interactive examples, see the component documentation.
Key Features
- Custom Cell Renderers: Full control over cell content with RenderFragment for complex visualizations and interactions
- Full C# Support: Comprehensive type definitions with Dictionary-based row data for flexible data handling
- Three Pagination Modes: Client-side, server-side, and infinite scroll pagination support
- Row Selection: Single and multiple row selection with checkboxes, persistent across pagination
- Row Click Actions: Handle full-row clicks for navigation or detail actions without interfering with selection checkboxes
- Expandable Rows: Render arbitrary content beneath rows, with optional expand/collapse toggle
- Extensive Column Configuration: Control width, resizing, hiding, and custom headers with flexible configuration options
- Blazor Integration: Native Blazor component with full event handling and state management support
Basic Usage
The simplest implementation requires providing column definitions and row data:
@using NovaComponents
<NvDatatable Columns="@employeeColumns" Rows="@employeeData" />
@code {
private List<NvDatatableColumn> employeeColumns = new()
{
new() { Field = "Name", HeaderName = "Full Name" },
new() { Field = "Email", HeaderName = "Email Address" },
new() { Field = "Department", HeaderName = "Department" },
new() { Field = "Age", HeaderName = "Age" },
new() { Field = "Salary", HeaderName = "Salary" },
};
private List<Dictionary<string, object?>> employeeData = new()
{
new()
{
["Name"] = "John Smith",
["Email"] = "john.smith@company.com",
["Department"] = "Engineering",
["Age"] = 32,
["Salary"] = 75000
},
// ... more rows
};
}
Advanced Column Configuration
Columns support extensive configuration options for precise control. View the full column configuration reference for details.
<NvDatatable Columns="@advancedColumns" Rows="@productData">
<NvDatatableCellTemplate Field="Name" Context="cell">
<div class="font-semibold">@cell.Value</div>
</NvDatatableCellTemplate>
<NvDatatableCellTemplate Field="Price" Context="cell">
<span class="font-mono text-feedback-success-low">
$@(((decimal)cell.Value!).ToString("F2"))
</span>
</NvDatatableCellTemplate>
<NvDatatableCellTemplate Field="Status" Context="cell">
<NvBadge
Label="@cell.Value?.ToString()"
Color="@(cell.Value?.ToString() == "Active" ? "success" : "error")" />
</NvDatatableCellTemplate>
</NvDatatable>
@code {
private List<NvDatatableColumn> advancedColumns = new()
{
new() { Field = "Name", HeaderName = "Product Name", Width = 200, Resizable = true },
new() { Field = "Price", HeaderName = "Price", Width = 120 },
new() { Field = "Status", HeaderName = "Status" }, // No width - takes remaining space
};
}
Data Modeling
NvDatatable consumes rows as a List<Dictionary<string, object?>>. When starting from strongly typed models, map them to dictionaries:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string Department { get; set; } = string.Empty;
public int Salary { get; set; }
}
// Extension method to convert to dictionary
public static Dictionary<string, object?> ToRow(this Employee e) => new()
{
["Id"] = e.Id,
["Name"] = e.Name,
["Email"] = e.Email,
["Department"] = e.Department,
["Salary"] = e.Salary,
};
// Usage
var employees = GetEmployees(); // List<Employee>
var rows = employees.Select(e => e.ToRow()).ToList();
Automatic Column Generation
When you don't provide column definitions, NvDatatable inspects the row data and builds the columns for you. This is handy for quickly displaying data without wiring up a column for every field.
private List<Dictionary<string, object?>> rows = new()
{
new() { ["Id"] = 1, ["FirstName"] = "Ada Lovelace", ["Salary"] = 95000, ["IsActive"] = true, ["StartDate"] = new DateOnly(2021, 3, 15) },
new() { ["Id"] = 2, ["FirstName"] = "Alan Turing", ["Salary"] = 88000, ["IsActive"] = false, ["StartDate"] = new DateOnly(2022, 7, 1) },
};
@* Omit Columns — the datatable infers them from the row data *@
<NvDatatable Rows="@rows" Sorting="@(new NvDatatableSortingConfig())" />
The generated columns follow these rules:
- One column per key found in the data (the union of keys across the first rows, in first-seen order).
- Headers are humanized from field names —
FirstNamebecomes "First Name",start_datebecomes "Start Date". - Cells are rendered based on the inferred value type:
- Boolean → centered
True/Falsetext - Number → right-aligned
- Date (
DateTime,DateOnly,DateTimeOffset, or an ISO date string) → culture-formatted - Array of objects → expandable row detail with a nested auto-generated datatable
- Array of primitives → comma-joined list
- Plain object → compact JSON
- String → rendered as-is
- Boolean → centered
- Sorting and filtering keep operating on the raw underlying values, not the formatted display text.
- Explicit columns always take precedence — set
Columnsto override any or all of the generated columns.
Tip: You can control cell alignment on any column (generated or explicit) with the
Alignproperty:NvDatatableColumnAlign.Left | Center | Right.
Master-detail from nested object collections
When a field's values are collections of objects (e.g. List<Dictionary<string, object?>>), auto-generation does not render them as a column — it promotes them to an expandable row detail containing a nested, auto-generated datatable:
- Each such field becomes its own labelled section (humanized field name) with its own nested datatable, which auto-generates its columns the same way (recursively).
- A model with several nested-object fields produces several stacked detail sections under a single expand toggle on the row.
- If a given row's list is empty, that section is omitted for that row.
- Collections of primitives are not details — they stay a column rendered as a comma-joined list.
private List<Dictionary<string, object?>> rows = new()
{
new()
{
["id"] = 1, ["name"] = "Acme",
["orders"] = new List<Dictionary<string, object?>> { new() { ["orderId"] = "A-1", ["amount"] = 250 } },
["invoices"] = new List<Dictionary<string, object?>> { new() { ["invoiceId"] = "INV-1", ["total"] = 250, ["paid"] = true } }
}
};
// `orders` and `invoices` become two stacked detail tables; `id`/`name` stay columns.
<NvDatatable Rows="@rows" />
Master-detail relies on the datatable's expandable system, currently available in React and Blazor.
Columns
Each column definition supports the following properties:
| Property | Required | Type | Description |
|---|---|---|---|
Field | ✅ | string | The key from your data object to display |
HeaderName | - | string | Custom header text (defaults to field name) |
Width | - | int? | Column width in pixels |
Align | - | NvDatatableColumnAlign? | Horizontal alignment of the column's cell content. Explicit columns default to left; auto-generated columns default to center (numbers right-aligned) |
Resizable | - | bool | Whether users can resize the column (default: true) |
Hidden | - | bool | Hide the column from display |
ValueFormatter | - | Func<NvTableRenderCellParams, object?> | Transform the raw value before rendering |
RenderCell | - | RenderFragment<NvTableRenderCellParams> | Custom cell rendering function |
Value Formatters
The ValueFormatter function transforms raw cell values before rendering, providing a clean way to handle common data transformations without requiring full render functions.
When to Use ValueFormatter vs RenderCell
- Use
ValueFormatterwhen you need to transform data to a different format (dates, arrays, nested objects) but don't need custom components or styling - Use
RenderCellwhen you need custom presentation with styled components, badges, buttons, or complex layouts - Use both together to first transform the data with
ValueFormatter, then style it withRenderCell
Function Signature
public Func<NvTableRenderCellParams, object?>? ValueFormatter { get; set; }
Function Parameters:
The function receives a single NvTableRenderCellParams object with the following properties:
| Parameter | Type | Description |
|---|---|---|
Value | object? | The raw cell value from the data |
Row | Dictionary<string, object?> | The complete row object (useful for accessing other fields) |
Field | string | The field name being formatted |
RowIndex | int | Zero-based row index |
Returns: An object? that will be passed to RenderCell or templates. The return value becomes the new Value in the cell parameters.
Common Use Cases
Format Currency:
new NvDatatableColumn
{
Field = "Price",
HeaderName = "Price",
ValueFormatter = context => $"${((decimal)context.Value!):F2}",
RenderCell = context => @<text>
<span class="font-mono">@context.Value</span>
</text>
}
Format Dates:
new NvDatatableColumn
{
Field = "BirthDate",
HeaderName = "Birth Date",
ValueFormatter = context => ((DateTime)context.Value!).ToString("MMMM d, yyyy"),
}
Join Arrays:
new NvDatatableColumn
{
Field = "Tags",
HeaderName = "Tags",
ValueFormatter = context =>
{
var tags = JsonSerializer.Deserialize<string[]>((string)context.Value!);
return tags != null ? string.Join(", ", tags) : string.Empty;
},
}
Transform Booleans:
new NvDatatableColumn
{
Field = "IsActive",
HeaderName = "Status",
ValueFormatter = context => (bool)context.Value! ? "Active" : "Inactive",
RenderCell = context => @<text>
<NvBadge
Label="@context.Value?.ToString()"
Color="@(context.Value?.ToString() == "Active" ? "success" : "neutral")" />
</text>
}
Combining ValueFormatter with RenderCell
You can use both together - the ValueFormatter runs first to transform the data, then RenderCell handles the presentation:
new NvDatatableColumn
{
Field = "Price",
HeaderName = "Price",
// First, format the decimal to a currency string
ValueFormatter = context => $"${((decimal)context.Value!):F2}",
// Then, style it with custom rendering
RenderCell = context => @<text>
<span class="font-mono text-feedback-success-low">
@context.Value
</span>
</text>
}
Combining ValueFormatter with Templates
The formatted value automatically flows to templates:
<NvDatatable Columns="@columns" Rows="@rows">
<!-- Template receives FORMATTED value (string) -->
<NvDatatableCellTemplate Field="Tags" Context="cell">
<div class="text-sm">@cell.Value</div>
<!-- Value is "JavaScript, React, TypeScript", not an array -->
</NvDatatableCellTemplate>
</NvDatatable>
@code {
private List<NvDatatableColumn> columns = new()
{
new()
{
Field = "Tags", // Original type: JSON string representing array
ValueFormatter = context =>
{
var tags = JsonSerializer.Deserialize<string[]>((string)context.Value!);
return tags != null ? string.Join(", ", tags) : string.Empty;
},
// Template receives the string, not the array
},
};
}
Custom Cell Renderers
There are two ways to customize cell rendering: templates (recommended) or RenderFragment.
Option 1: Templates (Recommended)
Use <NvDatatableCellTemplate> for clean, markup-based cell customization. Each column can have its own template specified by the Field parameter.
Template Parameters:
| Parameter | Type | Description |
|---|---|---|
Value | object? | The cell's actual value |
Row | Dictionary<string, object?> | Complete row object for accessing other fields |
Field | string | The field name being rendered |
RowIndex | int | Zero-based row index |
Examples:
<NvDatatable Columns="@columns" Rows="@products">
<!-- Format currency -->
<NvDatatableCellTemplate Field="Price" Context="cell">
<span class="font-mono">
$@(((decimal)cell.Value!).ToString("F2"))
</span>
</NvDatatableCellTemplate>
<!-- Status badge -->
<NvDatatableCellTemplate Field="Status" Context="cell">
<NvBadge
Label="@cell.Value?.ToString()"
Color="@(cell.Value?.ToString() == "Active" ? "success" : "error")" />
</NvDatatableCellTemplate>
<!-- Actions with access to full row -->
<NvDatatableCellTemplate Field="Id" Context="cell">
<NvButton @onclick="() => EditProduct((int)cell.Value!)">Edit</NvButton>
<NvButton @onclick="() => DeleteProduct((int)cell.Value!)">Delete</NvButton>
</NvDatatableCellTemplate>
</NvDatatable>
@code {
private List<NvDatatableColumn> columns = new()
{
new() { Field = "Name", HeaderName = "Product Name" },
new() { Field = "Price", HeaderName = "Price" },
new() { Field = "Status", HeaderName = "Status" },
new() { Field = "Id", HeaderName = "Actions" },
};
}
Option 2: RenderFragment
Use RenderFragment when you need programmatic logic or when working in code-heavy contexts.
RenderCell Parameters: NvTableRenderCellParams
| Parameter | Type | Description |
|---|---|---|
Value | object? | The cell's actual value |
Row | Dictionary<string, object?> | Complete row object for accessing other fields |
Field | string | The field name being rendered |
RowIndex | int | Zero-based row index |
Examples:
@code {
private List<NvDatatableColumn> columns = new()
{
// Format currency
new NvDatatableColumn
{
Field = "Price",
HeaderName = "Price",
RenderCell = context => @<text>
<span class="font-mono">
$@(((decimal)context.Value!).ToString("F2"))
</span>
</text>
},
// Status badge
new NvDatatableColumn
{
Field = "Status",
HeaderName = "Status",
RenderCell = context => @<text>
<NvBadge
Label="@context.Value?.ToString()"
Color="@(context.Value?.ToString() == "Active" ? "success" : "error")" />
</text>
},
// Actions with access to full row
new NvDatatableColumn
{
Field = "Id",
HeaderName = "Actions",
RenderCell = context => @<text>
<NvButton @onclick="() => EditItem((int)context.Value!)">Edit</NvButton>
<NvButton @onclick="() => DeleteItem((int)context.Value!)">Delete</NvButton>
</text>
},
// Complex rendering with multiple row fields
new NvDatatableColumn
{
Field = "Rating",
HeaderName = "Rating",
RenderCell = context => @<text>
<div class="flex items-center gap-1">
<span class="text-yellow-500">@GetStarRating((decimal)context.Value!)</span>
<span class="text-sm text-gray-600 ml-1">
@(((decimal)context.Value!).ToString("F1"))
</span>
</div>
</text>
},
};
private string GetStarRating(decimal rating)
{
var filled = new string('★', (int)Math.Floor(rating));
var empty = new string('☆', 5 - (int)Math.Floor(rating));
return filled + empty;
}
}
Priority: If both a template and RenderCell are defined for the same column, the template takes precedence.
Custom Header Renderers
The RenderHeader property allows you to customize column headers with custom Blazor components, such as tooltips, icons, or styled text.
Function Parameters: NvTableRenderHeaderParams
| Parameter | Type | Description |
|---|---|---|
HeaderName | string | The display name for the column header (from HeaderName property or field name) |
Field | string | The field name being rendered |
Examples:
Header with Tooltip:
new NvDatatableColumn
{
Field = "Name",
HeaderName = "Full Name",
RenderHeader = context => @<NvTooltip Message="The employee's complete legal name" Placement="NvTooltip.PlacementEnum.top">
<span>@context.HeaderName</span>
</NvTooltip>
}
Header with Icon:
new NvDatatableColumn
{
Field = "Salary",
HeaderName = "Salary",
RenderHeader = context => @<span class="flex items-center gap-1">
@context.HeaderName
<NvIcon Name="cash-banknote" Size="sm" />
</span>
}
Header with Custom Styling:
new NvDatatableColumn
{
Field = "Priority",
HeaderName = "Priority",
RenderHeader = context => @<span class="text-feedback-error-low font-bold">
@context.HeaderName *
</span>
}
Complete Example with Multiple Custom Headers:
<NvDatatable Columns="@columns" Rows="@data" />
@code {
private List<NvDatatableColumn> columns = new()
{
new NvDatatableColumn
{
Field = "Name",
HeaderName = "Full Name",
RenderHeader = context => @<NvTooltip Message="Employee's legal name">
<span>@context.HeaderName</span>
</NvTooltip>
},
new NvDatatableColumn
{
Field = "Salary",
HeaderName = "Salary",
RenderHeader = context => @<span class="flex items-center gap-1">
@context.HeaderName
<NvIcon Name="info-circle" Size="sm" />
</span>
},
new NvDatatableColumn
{
Field = "Email",
HeaderName = "Email Address"
// No RenderHeader - uses default header rendering
},
new NvDatatableColumn
{
Field = "Status",
HeaderName = "Status",
RenderHeader = context => @<span class="text-feedback-error-low font-bold">
@context.HeaderName *
</span>
},
};
}
Column Width Best Practices
When configuring column widths, follow these guidelines for optimal behavior:
⚠️ Important: Do not set width on ALL columns. Always leave at least one column without a specified width to take up the remaining space. Setting widths on every column can cause column resizing to behave incorrectly due to browser table rendering constraints.
Good Practice:
var columns = new List<NvDatatableColumn>
{
new() { Field = "Id", Width = 80 }, // Fixed narrow column
new() { Field = "Name", Width = 200 }, // Fixed wider column
new() { Field = "Email" }, // No width - takes remaining space
new() { Field = "Actions", Width = 150 }, // Fixed action column
};
Avoid:
var columns = new List<NvDatatableColumn>
{
new() { Field = "Id", Width = 80 }, // ❌ All columns have width
new() { Field = "Name", Width = 200 }, // ❌ Can cause resizing issues
new() { Field = "Email", Width = 300 }, // ❌ Browser table constraints
new() { Field = "Actions", Width = 150 }, // ❌ No flexible column
};
Tips:
- Set fixed widths for columns with predictable content (IDs, actions, status badges)
- Leave content columns (names, descriptions) without fixed widths for flexibility
- Use horizontal scrolling for tables with many columns rather than cramming them into viewport
- Note: Even with fixed widths, columns may still expand if:
- Users manually resize columns (when resizable is enabled)
- Content is too wide to fit and cannot be wrapped or collapsed (browser will auto-expand to prevent overflow)
Mode
NvDatatable uses a single top-level Mode parameter to control whether operations (pagination, sorting, filtering) are handled client-side or server-side. This replaces the previous per-feature mode settings.
public enum NvDatatableMode
{
Client, // Default - all operations handled in browser
Server // Operations require server callbacks
}
Usage:
- Client mode (default): Omit the
Modeparameter or setMode="NvDatatableMode.Client". All data is passed toRows, and pagination/sorting/filtering happen in the browser. - Server mode: Set
Mode="NvDatatableMode.Server". Parent component handles data fetching via callbacks (OnPaginationChange,OnSortingChange,OnFilterChange).
Pagination
NvDatatable supports three pagination modes to handle different data loading scenarios:
Pagination Modes
- Client-Side Pagination: All data is loaded at once, pagination handled in the browser
- Server-Side Pagination: Data fetched page-by-page from server with button navigation
- Infinite Scroll: Data loads continuously as user scrolls, accumulating all loaded rows
Client-Side Pagination
Best for datasets under a few thousand rows where all data can be loaded at once. Uses the default client mode.
Enable pagination: pass the Pagination parameter. Default UI: omit <PaginationTemplate> to use the built-in NvPaginationtable component.
@using NovaComponents
<!-- Enable pagination + use default NvPaginationtable (no PaginationTemplate) -->
<NvDatatable
Columns="@columns"
Rows="@allData"
Pagination="@(new NvDatatablePaginationConfig
{
InitialPageSize = 20,
PageSizeOptions = new[] { 10, 20, 50, 100 }
})" />
@code {
private List<NvDatatableColumn> columns = new()
{
new() { Field = "Id", HeaderName = "ID" },
new() { Field = "Name", HeaderName = "Name" },
new() { Field = "Email", HeaderName = "Email" },
new() { Field = "Department", HeaderName = "Department" },
};
private List<Dictionary<string, object?>> allData = GenerateEmployeeData(250);
private static List<Dictionary<string, object?>> GenerateEmployeeData(int count)
{
var departments = new[] { "Engineering", "Marketing", "Sales", "HR", "Finance", "Operations" };
var data = new List<Dictionary<string, object?>>();
for (int i = 1; i <= count; i++)
{
data.Add(new Dictionary<string, object?>
{
["Id"] = i,
["Name"] = $"Employee {i}",
["Email"] = $"employee{i}@company.com",
["Department"] = departments[i % departments.Length]
});
}
return data;
}
}
What you'll see:
- A table with 250 rows of employee data
- The default
NvPaginationtablecomponent automatically rendered below the table - Navigation controls showing "Page 1 of 13" (with 20 rows per page)
- A page size selector allowing users to change rows per page
- All pagination logic handled automatically by the table
💡 See it in action: Check out the
ClientPaginationDefaultstory in Storybook for an interactive example of this default pagination behavior.
Custom pagination UI: use <PaginationTemplate> to render your own controls:
<NvDatatable
Columns="@columns"
Rows="@allData"
Pagination="@(new NvDatatablePaginationConfig
{
InitialPageSize = 20,
PageSizeOptions = new[] { 10, 20, 50, 100 }
})">
<PaginationTemplate Context="api">
<div style="margin-top: 16px; display: flex; gap: 16px; align-items: center;">
<NvButton @onclick="api.PreviousPage" Disabled="@(!api.CanPreviousPage)">
Previous
</NvButton>
<span>Page @(api.PageIndex + 1) of @api.PageCount</span>
<NvButton @onclick="api.NextPage" Disabled="@(!api.CanNextPage)">
Next
</NvButton>
<select @onchange="@((ChangeEventArgs e) => api.SetPageSize(int.Parse(e.Value?.ToString() ?? "10")))">
@foreach (var size in new[] { 10, 20, 50 })
{
<option value="@size" selected="@(api.PageSize == size)">@size rows</option>
}
</select>
</div>
</PaginationTemplate>
</NvDatatable>
Key Points:
- Pass all data to the
Rowsparameter - Table handles pagination logic internally
- Default UI: When
<PaginationTemplate>is not provided, the datatable automatically rendersNvPaginationtablecomponent (client mode only) - Use
<PaginationTemplate>child content to create custom controls - No server requests needed for page changes
Server-Side Pagination
Best for large datasets where you want to fetch data page-by-page. Requires Mode="NvDatatableMode.Server" on the component.
⚠️ Important: In server-side mode, the default NvPaginationtable component is not automatically rendered. You must provide a <PaginationTemplate> to display pagination controls. Use the NvPaginationtable component inside the template to get the standard pagination UI:
<NvDatatable
Columns="@columns"
Rows="@currentPageData"
Mode="NvDatatableMode.Server"
Pagination="@(new NvDatatablePaginationConfig
{
TotalRowCount = totalCount,
InitialPageSize = 10,
OnPaginationChange = HandlePaginationChange
})">
<PaginationTemplate Context="api">
<NvPaginationtable
PageIndex="@api.PageIndex"
PageSize="@api.PageSize"
PageCount="@api.PageCount"
RowCount="@api.RowCount"
PageIndexChanged="@((double? index) => { if (index.HasValue) api.SetPageIndex((int)index.Value); })"
PageSizeChangedEvent="@((double? size) => { if (size.HasValue) api.SetPageSize((int)size.Value); })" />
</PaginationTemplate>
</NvDatatable>
@code {
private List<Dictionary<string, object?>> currentPageData = new();
private int currentPage = 0;
private int pageSize = 10;
private int totalCount = 0;
// Fetch only current page data
private async Task FetchData()
{
var response = await Http.GetFromJsonAsync<PagedResponse>(
$"/api/users?page={currentPage + 1}&limit={pageSize}");
currentPageData = response.Data;
totalCount = response.Total;
StateHasChanged();
}
private void HandlePaginationChange(NvDatatablePaginationState state)
{
currentPage = state.PageIndex;
pageSize = state.PageSize;
_ = FetchData();
}
protected override async Task OnInitializedAsync()
{
await FetchData();
}
}
Key Points:
- ⚠️ Required: You must provide
<PaginationTemplate>to display pagination controls (no default UI in server mode). UseNvPaginationtableinside the template for the standard pagination UI - Pass only current page data to
Rowsparameter (data is replaced on page change) - Provide
TotalRowCountorTotalPageCount - Use
OnPaginationChangecallback to fetch new data - Parent component manages which page to display
Infinite Scroll
Best for continuously loading data as user scrolls, like social media feeds. Requires Mode="NvDatatableMode.Server" and Infinite = true in the pagination config.
<div style="max-height: 600px; overflow: auto;">
<NvDatatable
StickyHeader="true"
Columns="@columns"
Rows="@loadedData"
Mode="NvDatatableMode.Server"
Pagination="@(new NvDatatablePaginationConfig
{
Infinite = true,
HasMore = hasMore,
IsLoading = isLoading,
LoadMoreThreshold = 500,
OnLoadMore = LoadMore
})">
<PaginationTemplate Context="api">
@if (api.IsLoading == true)
{
<div style="padding: 24px; text-align: center;">Loading more...</div>
}
else if (api.HasMore == true)
{
<div style="padding: 16px; text-align: center;">Scroll to load more</div>
}
else
{
<div style="padding: 16px; text-align: center; font-weight: bold;">
All @api.RowCount rows loaded
</div>
}
</PaginationTemplate>
</NvDatatable>
</div>
@code {
private List<Dictionary<string, object?>> loadedData = new();
private bool isLoading = false;
private bool hasMore = true;
private int currentPage = 1;
private async Task LoadMore()
{
if (isLoading || !hasMore) return;
isLoading = true;
StateHasChanged();
var response = await Http.GetFromJsonAsync<PagedResponse>(
$"/api/users?page={currentPage}&limit=20");
loadedData.AddRange(response.Data); // Append new data
currentPage++;
hasMore = loadedData.Count < response.Total;
isLoading = false;
StateHasChanged();
}
protected override async Task OnInitializedAsync()
{
await LoadMore(); // Load initial data
}
}
Key Points:
- Pass accumulated data to
Rowsparameter (data is appended on load) - Wrap table in scrollable container or let it grow naturally
- Uses IntersectionObserver to detect when last row is near viewport
- Parent component maintains accumulated data array
- Set
HasMore = falsewhen all data is loaded
Pagination Configuration
public class NvDatatablePaginationConfig
{
// Common properties
public int? InitialPageSize { get; set; } // Default: 10
public int[]? PageSizeOptions { get; set; } // Default: [10, 20, 50, 100]
// Server-side specific (requires Mode="NvDatatableMode.Server" on component)
public int? TotalRowCount { get; set; }
public int? TotalPageCount { get; set; }
public Action<NvDatatablePaginationState>? OnPaginationChange { get; set; }
// Infinite scroll specific (requires Mode="NvDatatableMode.Server" + Infinite = true)
public bool Infinite { get; set; } // Enable infinite scroll
public bool? HasMore { get; set; }
public bool? IsLoading { get; set; }
public int? LoadMoreThreshold { get; set; } // Default: 500 (pixels)
public Func<Task>? OnLoadMore { get; set; }
}
Note: The pagination Mode property has been removed. Use the top-level Mode parameter on NvDatatable to set client/server mode. For infinite scroll, set Infinite = true in the pagination config along with Mode="NvDatatableMode.Server" on the component.
Pagination API
Default Pagination Behavior:
- Client mode: When
<PaginationTemplate>is not provided, the datatable automatically renders theNvPaginationtablecomponent with full pagination controls. - Server mode: When
<PaginationTemplate>is not provided, no pagination UI is displayed. You must provide<PaginationTemplate>with aNvPaginationtablecomponent inside to display the standard pagination controls.
Custom Pagination:
The <PaginationTemplate> child content receives an API object with these properties and methods:
public class NvDatatableRenderPaginationAPI
{
// Current state
public int PageIndex { get; set; } // Current page (zero-based)
public int PageSize { get; set; } // Rows per page
public int PageCount { get; set; } // Total number of pages
public int RowCount { get; set; } // Total number of rows
// Navigation methods
public Action FirstPage { get; set; } // Go to first page
public Action PreviousPage { get; set; } // Go to previous page
public Action NextPage { get; set; } // Go to next page
public Action LastPage { get; set; } // Go to last page
public Action<int> SetPageIndex { get; set; } // Go to specific page
public Action<int> SetPageSize { get; set; } // Change page size
// State queries
public bool CanPreviousPage { get; set; } // Can navigate backward
public bool CanNextPage { get; set; } // Can navigate forward
// Infinite scroll only
public bool? IsLoading { get; set; } // Currently loading data
public bool? HasMore { get; set; } // More data available
}
Expandable Rows
NvDatatable supports rendering arbitrary content beneath rows via the Expandable parameter. Two modes are available: always-visible (content is persistently shown) and collapsible (content is hidden behind an expand/collapse toggle).
Configuration
| Property | Type | Description |
|---|---|---|
RenderExpandedContent | Func<NvDatatableExpandedContentParams, RenderFragment?> | Required. Return the content to render beneath a row, or null for no content. |
Collapsible | bool | When true, shows an expand/collapse toggle and hides content by default. (default: false) |
ExpandedState | Dictionary<string, bool>? | Controlled expanded state (collapsible only), keyed by row id. To expand all rows, populate the dictionary with every row id mapped to true. |
OnExpandedChange | Action<Dictionary<string, bool>>? | Callback when expanded state changes (collapsible only). |
GetRowCanExpand | Func<Dictionary<string, object?>, bool>? | Control which rows can be expanded (collapsible only). When omitted, all rows can expand. |
ToggleColumnWidth | int | Width of the expand toggle column in pixels (default: 48). |
Row identity for expanded state derives from Selection.GetRowId when selection is configured, otherwise it falls back to the visible row index as a string (matching the React/TanStack default).
Parity caveat: TanStack's React
ExpandedStateacceptstrueas an "expand all" sentinel. The Blazor surface uses a plainDictionary<string, bool>; to expand all rows, populate the dictionary with every row id mapped totrue.
Always-Visible Content
When Collapsible is false (default), expanded content renders persistently beneath each row that returns non-null content:
<NvDatatable Columns="@columns"
Rows="@rows"
Expandable="@(new NvDatatableExpandableConfig
{
RenderExpandedContent = ctx => @<p>Details for @ctx.Row["Name"]</p>
})" />
Rows where RenderExpandedContent returns null render normally without expanded content.
Collapsible Content
Set Collapsible = true to add an expand/collapse toggle column. Rows are collapsed by default:
<NvDatatable Columns="@columns"
Rows="@rows"
Expandable="@(new NvDatatableExpandableConfig
{
Collapsible = true,
RenderExpandedContent = ctx => @<p>Details for @ctx.Row["Name"]</p>
})" />
Controlled Expanded State
Use ExpandedState and OnExpandedChange to drive expand/collapse behaviour from parent state:
@code {
private Dictionary<string, bool> expandedState = new();
}
<NvDatatable Columns="@columns"
Rows="@rows"
Expandable="@(new NvDatatableExpandableConfig
{
Collapsible = true,
ExpandedState = expandedState,
OnExpandedChange = state =>
{
expandedState = state;
StateHasChanged();
},
RenderExpandedContent = ctx => @<p>Details for @ctx.Row["Name"]</p>
})" />
To expand every row at once, populate expandedState with every row id mapped to true.
Combining with Selection
Expandable rows work alongside row selection. When both Selection and Expandable.Collapsible are enabled, the checkbox and the expand toggle share a single combined prefix column, with the two controls laid out side-by-side. The column width is the sum of Selection.CheckboxColumnWidth and Expandable.ToggleColumnWidth (both default to 48px, so the combined column defaults to 96px):
<NvDatatable Columns="@columns"
Rows="@rows"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids; StateHasChanged(); }
})"
Expandable="@(new NvDatatableExpandableConfig
{
Collapsible = true,
RenderExpandedContent = ctx => @<p>Details for @ctx.Row["Name"]</p>
})" />
Accessibility
- The expand/collapse toggle uses
aria-expandedandaria-controlslinking to the expanded content region. - The expanded content row has
role="region"with an accessible label that matches the toggle. - The toggle is keyboard-operable via
EnterandSpace(handled by the underlyingNvIconbutton).
Interaction Behavior
- Clicking the expand toggle does not trigger
OnRowClickor selection changes (the prefix cell stops propagation). - Expanded content is independent of sorting, filtering, and pagination state.
- When a row is filtered out, its expanded content is naturally hidden.
Horizontal Scrolling
For tables with many columns or wide content, enable horizontal scrolling by adding CSS classes:
<NvDatatable
Columns="@columns"
Rows="@data"
class="block overflow-x-auto" />
Sticky Header
Enable sticky headers to keep column headers visible when scrolling through long tables. This is especially useful for tables with many rows where you want to maintain context of what each column represents.
<NvDatatable
Columns="@columns"
Rows="@data"
StickyHeader="true" />
Sorting
NvDatatable provides comprehensive sorting capabilities with support for both client-side and server-side sorting, multi-column sorting, custom sort functions, and fine-grained control over sort behavior.
Sorting Modes
- Client-Side Sorting: All data is sorted in the browser automatically
- Server-Side Sorting: Sorting is handled by your API, table displays sorted results
Client-Side Sorting
Best for datasets that are fully loaded in the browser. The table automatically handles all sorting logic. Uses the default client mode.
<NvDatatable
Columns="@columns"
Rows="@allData"
Sorting="@(new NvDatatableSortingConfig
{
EnableMultiSort = false, // Single column sorting (default)
EnableSortingRemoval = true, // Allow cycling through none state
SortDescFirst = false // Start with ascending (default)
})" />
@code {
private List<NvDatatableColumn> columns = new()
{
new() { Field = "Id", HeaderName = "ID", Width = 80 },
new() { Field = "Name", HeaderName = "Product Name" },
new() { Field = "Price", HeaderName = "Price", Width = 120 },
new() { Field = "Stock", HeaderName = "In Stock", Width = 100 },
};
private List<Dictionary<string, object?>> allData = new()
{
new() { ["Id"] = 1, ["Name"] = "Product A", ["Price"] = 29.99, ["Stock"] = 100 },
new() { ["Id"] = 2, ["Name"] = "Product B", ["Price"] = 19.99, ["Stock"] = 50 },
// ... more data
};
}
Key Points:
- All data must be loaded in the
Rowsparameter - Sorting happens instantly in the browser
- No server requests needed
- Works seamlessly with client-side pagination
Initial Sort State (Uncontrolled)
When you want the table to start sorted by a specific column but still let users change the sort by clicking headers, use InitialSortState. It seeds the internal sort state on first render only — unlike SortState, it does not make the component controlled.
<NvDatatable
Columns="@columns"
Rows="@products"
Sorting="@(new NvDatatableSortingConfig
{
InitialSortState = new NvDatatableSortingState
{
new NvDatatableSortColumn { Id = "Price", Desc = true }
}
})" />
When to use which:
InitialSortState: your API returns unsorted data and you want a sensible default sort, but users should still be able to re-sort freely.SortState+OnSortingChange: you need full control over sorting (e.g. server-side sorting, URL sync). PassingSortStatemakes the component controlled, so header clicks only take effect if you updateSortStateyourself in the callback.
If both SortState and InitialSortState are provided, SortState wins.
Server-Side Sorting
Best for large datasets where sorting is performed by your backend API. Requires Mode="NvDatatableMode.Server" on the component.
<NvDatatable
Columns="@columns"
Rows="@currentData"
Mode="NvDatatableMode.Server"
Sorting="@(new NvDatatableSortingConfig
{
SortState = sortState,
EnableSortingRemoval = true,
OnSortingChange = HandleSortingChange
})" />
@code {
private List<Dictionary<string, object?>> currentData = new();
private NvDatatableSortingState sortState = new();
private void HandleSortingChange(NvDatatableSortingState newSortState)
{
sortState = newSortState;
// Extract sort parameters for API call
var sortBy = newSortState.FirstOrDefault()?.Id;
var sortOrder = newSortState.FirstOrDefault()?.Desc == true ? "desc" : "asc";
// Fetch sorted data from API
_ = FetchData(sortBy, sortOrder);
}
private async Task FetchData(string? sortBy = null, string? sortOrder = "asc")
{
var response = await Http.GetFromJsonAsync<DataResponse>(
$"/api/products?sortBy={sortBy}&sortOrder={sortOrder}");
currentData = response.Data;
StateHasChanged();
}
protected override async Task OnInitializedAsync()
{
await FetchData();
}
}
Key Points:
- Pass pre-sorted data to
Rowsparameter - Use
SortStateto control which columns are sorted - Implement
OnSortingChangecallback to fetch new data - Parent component manages sort state and data fetching
SortingState Format:
// Single column sort
var sortState = new NvDatatableSortingState
{
new NvDatatableSortColumn { Id = "Price", Desc = true }
};
// Multi-column sort
var sortState = new NvDatatableSortingState
{
new NvDatatableSortColumn { Id = "Department", Desc = false },
new NvDatatableSortColumn { Id = "Salary", Desc = true }
};
Column-Level Sorting Options
Each column can have individual sorting configuration:
var columns = new List<NvDatatableColumn>
{
new()
{
Field = "Id",
Sortable = false, // Disable sorting for this column
},
new()
{
Field = "Name",
SortDescFirst = true, // Start with descending when clicked
},
new()
{
Field = "Rank",
InvertSorting = true, // Lower numbers are better (rank 1 > rank 10)
},
new()
{
Field = "Score",
SortUndefined = 1, // Put null/undefined values at the end (the default; -1 for beginning)
},
new()
{
Field = "Status",
// Custom sorting function
SortingFn = (rowA, rowB) =>
{
var statusOrder = new Dictionary<string, int>
{
{ "active", 1 },
{ "pending", 2 },
{ "inactive", 3 }
};
var statusA = rowA["Status"]?.ToString() ?? "";
var statusB = rowB["Status"]?.ToString() ?? "";
var orderA = statusOrder.ContainsKey(statusA) ? statusOrder[statusA] : 999;
var orderB = statusOrder.ContainsKey(statusB) ? statusOrder[statusB] : 999;
return orderA.CompareTo(orderB);
}
},
};
SortingFn contract: the function receives the two full row dictionaries and returns a negative value when the first row sorts earlier, zero for a tie, or a positive value when it sorts later (ascending contract; a descending sort reverses the result). Null cells are placed by SortUndefined before the function is consulted, unless both cells are null, and a result of zero falls through to the next column in a multi-sort. Without a SortingFn, string columns sort with a culture-independent, case-insensitive (ordinal) comparison — provide a SortingFn when you need culture-specific collation.
Multi-Column Sorting
Enable users to sort by multiple columns simultaneously:
<NvDatatable
Columns="@columns"
Rows="@data"
Sorting="@(new NvDatatableSortingConfig
{
EnableMultiSort = true,
MaxMultiSortColCount = 3 // Limit to 3 columns (optional)
})" />
Usage:
- When
EnableMultiSortis true, each click adds to the sort rather than replacing it - Click a header to sort by that column
- Click another header to add secondary sort
- Continue clicking to add more sort columns
- Click a currently sorted column to toggle between ascending/descending/none
Sorting with Value Formatters
⚠️ Important: When using ValueFormatter with sorting, be aware that sorting operates on the original value, not the formatted value. This ensures accurate sorting.
var columns = new List<NvDatatableColumn>
{
new()
{
Field = "Price",
HeaderName = "Price",
// Format for display
ValueFormatter = context => $"${((decimal)context.Value!):F2}",
// Sorting uses original decimal value automatically ✓
},
new()
{
Field = "Date",
HeaderName = "Date",
// Format date for display
ValueFormatter = context => ((DateTime)context.Value!).ToString("MMMM d, yyyy"),
// Sorting uses original DateTime value ✓
},
};
Why This Works:
- Sorting reads values directly from the row data (original values)
ValueFormatteronly affects display, not sorting- This is different from React where
valueFormattercan affect sorting
Handling Null Values
Control where null and undefined values appear in sorted results:
new NvDatatableColumn
{
Field = "OptionalField",
SortUndefined = 1, // Options: -1 (first) or 1 (last)
}
| Value | Behavior |
|---|---|
-1 | Null values appear first |
1 | Null values appear last (default) |
Placement is direction-relative, matching TanStack Table's numeric sortUndefined: with the default 1, nulls appear last when sorting ascending and first when sorting descending. InvertSorting flips the placement as well.
Inverted Sorting
For rankings or scenarios where lower numbers are better:
new NvDatatableColumn
{
Field = "Rank",
HeaderName = "Rank",
InvertSorting = true, // Rank 1 will appear before rank 10 in "ascending" sort
}
Sorting Configuration Reference
Global Sorting Config (Sorting parameter):
public class NvDatatableSortingConfig
{
public bool EnableMultiSort { get; set; } // Default: false
public bool EnableSortingRemoval { get; set; } // Default: true
public int? MaxMultiSortColCount { get; set; } // Max columns for multi-sort
public bool SortDescFirst { get; set; } // Default: false
// Uncontrolled initial sort applied on first render; ignored when SortState is set
public NvDatatableSortingState? InitialSortState { get; set; }
// Server-side specific (requires Mode="NvDatatableMode.Server" on component)
public NvDatatableSortingState? SortState { get; set; } // Controlled sort state
public Action<NvDatatableSortingState>? OnSortingChange { get; set; }
}
Note: The sorting Mode property has been removed. Sorting behavior is derived from the top-level Mode parameter on NvDatatable. For server-side sorting, set Mode="NvDatatableMode.Server" on the component and use OnSortingChange callback.
Column-Level Sorting Options:
public class NvDatatableColumn
{
public bool Sortable { get; set; } // Default: true
public Func<Dictionary<string, object?>,
Dictionary<string, object?>, int>? SortingFn { get; set; }
public bool SortDescFirst { get; set; } // Default: false
public bool InvertSorting { get; set; } // Default: false
public int SortUndefined { get; set; } // Default: 1 (last)
}
Complete Example: Client-Side Sorting with Pagination
<NvDatatable
Columns="@columns"
Rows="@products"
StickyHeader="true"
Sorting="@(new NvDatatableSortingConfig
{
EnableMultiSort = false,
EnableSortingRemoval = true
})"
Pagination="@(new NvDatatablePaginationConfig
{
InitialPageSize = 20
})">
<PaginationTemplate Context="api">
<div style="margin-top: 16px; display: flex; gap: 16px; align-items: center;">
<NvButton @onclick="api.PreviousPage" Disabled="@(!api.CanPreviousPage)">
Previous
</NvButton>
<span>Page @(api.PageIndex + 1) of @api.PageCount</span>
<NvButton @onclick="api.NextPage" Disabled="@(!api.CanNextPage)">
Next
</NvButton>
</div>
</PaginationTemplate>
</NvDatatable>
@code {
private List<NvDatatableColumn> columns = new()
{
new() { Field = "Id", HeaderName = "ID", Width = 60, Sortable = false },
new() { Field = "Name", HeaderName = "Product" },
new() { Field = "Category", HeaderName = "Category", Width = 150 },
new() { Field = "Price", HeaderName = "Price", Width = 100, SortDescFirst = true },
new() { Field = "Stock", HeaderName = "Stock", Width = 100 },
};
private List<Dictionary<string, object?>> products = new()
{
new() { ["Id"] = 1, ["Name"] = "Widget A", ["Category"] = "Tools", ["Price"] = 29.99, ["Stock"] = 45 },
new() { ["Id"] = 2, ["Name"] = "Gadget B", ["Category"] = "Electronics", ["Price"] = 149.99, ["Stock"] = 12 },
new() { ["Id"] = 3, ["Name"] = "Tool C", ["Category"] = "Tools", ["Price"] = 19.99, ["Stock"] = 89 },
// ... more products
};
}
Filtering
NvDatatable provides flexible global filtering capabilities with support for both client-side and server-side filtering modes. Build custom filter UIs using the FilteringTemplate parameter to create search inputs, dropdown filters, date pickers, and more.
Type-Safe Filtering with Generics
The NvDatatableFilteringConfig<TFilterState> class uses a generic type parameter to provide compile-time type safety for your filter state. This eliminates the need for casting and provides IntelliSense support in your filter functions.
Key Benefits:
- No casting required: Filter state is automatically typed in callbacks
- Compile-time checking: Type safety without runtime errors
- IntelliSense support: Full autocomplete for filter state properties in filter functions
- Better error messages: Catch type mismatches at build time, not runtime
Filtering Modes
- Client-Side Filtering: All data is filtered in the browser using a custom filter function
- Server-Side Filtering: Filtering is handled by your API using query parameters
Client-Side Filtering
Best for datasets that are fully loaded in the browser. The table evaluates your custom filter function against all rows instantly. Uses the default client mode.
<NvDatatable
Columns="@columns"
Rows="@allInvoices"
Filtering="@(new NvDatatableFilteringConfig<string>
{
FilterState = searchTerm,
OnFilterChange = newFilter => searchTerm = newFilter ?? "",
GlobalFilterFn = CustomFilterFunction,
DebounceMs = 300
})">
<FilteringTemplate Context="api">
<div style="margin-bottom: 16px;">
<input
type="text"
placeholder="Search invoices..."
value="@searchTerm"
@oninput="@((ChangeEventArgs e) => searchTerm = e.Value?.ToString() ?? "")"
style="padding: 8px; width: 300px;" />
<p>Showing @api.FilteredRows of @api.TotalRows invoices</p>
</div>
</FilteringTemplate>
</NvDatatable>
@code {
private string searchTerm = "";
private List<NvDatatableColumn> columns = new()
{
new() { Field = "InvoiceNumber", HeaderName = "Invoice #" },
new() { Field = "CustomerName", HeaderName = "Customer" },
new() { Field = "Amount", HeaderName = "Amount" },
new() { Field = "Status", HeaderName = "Status" },
};
private List<Dictionary<string, object?>> allInvoices = new()
{
new() { ["InvoiceNumber"] = "INV-001", ["CustomerName"] = "Acme Corp", ["Amount"] = 1500.00, ["Status"] = "paid" },
new() { ["InvoiceNumber"] = "INV-002", ["CustomerName"] = "Tech Inc", ["Amount"] = 2500.00, ["Status"] = "pending" },
// ... more data
};
// Custom filter function evaluates each row
private bool CustomFilterFunction(Dictionary<string, object?> row, string columnId, object? filterValue)
{
if (filterValue == null || string.IsNullOrWhiteSpace(filterValue.ToString()))
return true;
var searchLower = filterValue.ToString()!.ToLower();
// Search across multiple fields
var invoiceNumber = row["InvoiceNumber"]?.ToString()?.ToLower() ?? "";
var customerName = row["CustomerName"]?.ToString()?.ToLower() ?? "";
return invoiceNumber.Contains(searchLower) || customerName.Contains(searchLower);
}
}
Key Points:
- All data must be loaded in the
Rowsparameter - Your
GlobalFilterFnevaluates each row against the filter state - Filtering happens instantly with debouncing to prevent excessive re-renders
- Works seamlessly with client-side pagination and sorting
Multi-Criteria Filtering
For complex filtering with multiple inputs, use a class or record as your filter state:
<NvDatatable
Columns="@columns"
Rows="@allInvoices"
Filtering="@(new NvDatatableFilteringConfig<FilterState>
{
FilterState = filterState,
OnFilterChange = newFilter => filterState = newFilter ?? new FilterState(),
GlobalFilterFn = MultiCriteriaFilterFunction,
DebounceMs = 300
})">
<FilteringTemplate Context="api">
<div style="margin-bottom: 16px;">
<div style="display: flex; gap: 16px; margin-bottom: 12px;">
<input
type="text"
placeholder="Search..."
value="@filterState.SearchTerm"
@oninput="@((ChangeEventArgs e) =>
filterState = filterState with { SearchTerm = e.Value?.ToString() ?? "" })"
style="padding: 8px; flex: 1;" />
<select
value="@filterState.Status"
@onchange="@((ChangeEventArgs e) =>
filterState = filterState with { Status = e.Value?.ToString() ?? "" })"
style="padding: 8px;">
<option value="">All Statuses</option>
<option value="paid">Paid</option>
<option value="pending">Pending</option>
<option value="overdue">Overdue</option>
</select>
<input
type="number"
placeholder="Min amount"
value="@filterState.MinAmount"
@oninput="@((ChangeEventArgs e) =>
filterState = filterState with { MinAmount = decimal.TryParse(e.Value?.ToString(), out var result) ? result : 0 })"
style="padding: 8px; width: 150px;" />
</div>
<p>Showing @api.FilteredRows of @api.TotalRows invoices</p>
</div>
</FilteringTemplate>
</NvDatatable>
@code {
private record FilterState(string SearchTerm = "", string Status = "", decimal MinAmount = 0);
private FilterState filterState = new();
private bool MultiCriteriaFilterFunction(Dictionary<string, object?> row, string columnId, object? filterValue)
{
if (filterValue is not FilterState filter)
return true;
var rowData = row;
// Check search term (across multiple fields)
if (!string.IsNullOrWhiteSpace(filter.SearchTerm))
{
var searchLower = filter.SearchTerm.ToLower();
var invoiceNumber = rowData["InvoiceNumber"]?.ToString()?.ToLower() ?? "";
var customerName = rowData["CustomerName"]?.ToString()?.ToLower() ?? "";
if (!invoiceNumber.Contains(searchLower) && !customerName.Contains(searchLower))
return false;
}
// Check status filter
if (!string.IsNullOrWhiteSpace(filter.Status))
{
var rowStatus = rowData["Status"]?.ToString() ?? "";
if (rowStatus != filter.Status)
return false;
}
// Check amount filter
if (filter.MinAmount > 0)
{
var amount = Convert.ToDecimal(rowData["Amount"]);
if (amount < filter.MinAmount)
return false;
}
return true;
}
}
Server-Side Filtering
Best for large datasets where filtering is performed by your backend API. Requires Mode="NvDatatableMode.Server" on the component.
<NvDatatable
Columns="@columns"
Rows="@currentData"
Mode="NvDatatableMode.Server"
Pagination="@(new NvDatatablePaginationConfig
{
TotalRowCount = totalCount,
InitialPageSize = 10,
OnPaginationChange = HandlePaginationChange
})"
Sorting="@(new NvDatatableSortingConfig
{
SortState = sortState,
OnSortingChange = HandleSortingChange
})"
Filtering="@(new NvDatatableFilteringConfig<FilterState>
{
FilterState = filterState,
OnFilterChange = HandleFilterChange
})">
<FilteringTemplate Context="api">
<div style="margin-bottom: 16px;">
<div style="display: flex; gap: 16px; margin-bottom: 12px;">
<input
type="text"
placeholder="Search..."
value="@filterState.SearchTerm"
@oninput="@((ChangeEventArgs e) =>
filterState = filterState with { SearchTerm = e.Value?.ToString() ?? "" })"
style="padding: 8px; flex: 1;" />
<select
value="@filterState.Department"
@onchange="@((ChangeEventArgs e) =>
filterState = filterState with { Department = e.Value?.ToString() ?? "" })"
style="padding: 8px;">
<option value="">All Departments</option>
<option value="Engineering">Engineering</option>
<option value="Sales">Sales</option>
<option value="Marketing">Marketing</option>
</select>
</div>
@if (isLoading)
{
<p>Loading...</p>
}
else
{
<p>Showing @totalCount users @(hasActiveFilters ? "(filtered)" : "")</p>
}
</div>
</FilteringTemplate>
</NvDatatable>
@code {
private record FilterState(string SearchTerm = "", string Department = "", string Status = "");
private FilterState filterState = new();
private List<Dictionary<string, object?>> currentData = new();
private int currentPage = 0;
private int pageSize = 10;
private int totalCount = 0;
private NvDatatableSortingState sortState = new();
private bool isLoading = false;
private bool hasActiveFilters =>
!string.IsNullOrWhiteSpace(filterState.SearchTerm) ||
!string.IsNullOrWhiteSpace(filterState.Department) ||
!string.IsNullOrWhiteSpace(filterState.Status);
private void HandleFilterChange(object? newFilter)
{
filterState = (FilterState)newFilter!;
currentPage = 0; // Reset to page 1 when filters change
_ = FetchData();
}
private void HandlePaginationChange(NvDatatablePaginationState state)
{
currentPage = state.PageIndex;
pageSize = state.PageSize;
_ = FetchData();
}
private void HandleSortingChange(NvDatatableSortingState newSortState)
{
sortState = newSortState;
currentPage = 0; // Reset to page 1 when sorting changes
_ = FetchData();
}
private async Task FetchData()
{
isLoading = true;
StateHasChanged();
var queryParams = new Dictionary<string, string>
{
{ "_page", (currentPage + 1).ToString() },
{ "_per_page", pageSize.ToString() }
};
// Add filter parameters
if (!string.IsNullOrWhiteSpace(filterState.SearchTerm))
queryParams["_like"] = filterState.SearchTerm;
if (!string.IsNullOrWhiteSpace(filterState.Department))
queryParams["department"] = filterState.Department;
if (!string.IsNullOrWhiteSpace(filterState.Status))
queryParams["status"] = filterState.Status;
// Add sort parameters
var sortColumn = sortState.FirstOrDefault();
if (sortColumn != null)
{
queryParams["_sort"] = sortColumn.Id;
queryParams["_order"] = sortColumn.Desc ? "desc" : "asc";
}
var queryString = string.Join("&", queryParams.Select(kvp => $"{kvp.Key}={Uri.EscapeDataString(kvp.Value)}"));
var response = await Http.GetFromJsonAsync<PagedResponse>($"/api/users?{queryString}");
currentData = response.Data;
totalCount = response.Total;
isLoading = false;
StateHasChanged();
}
protected override async Task OnInitializedAsync()
{
await FetchData();
}
}
Key Points:
- Pass pre-filtered data to
Rowsparameter - Use
OnFilterChangecallback to update filter state and fetch new data - Reset
currentPageto 0 when filters change to show filtered results from the beginning - Parent component manages filter state and data fetching
- Combine with server-side pagination and sorting
Filter UI with Visual Feedback
Enhance user experience by showing active filters as dismissible chips:
<NvDatatable
Columns="@columns"
Rows="@data"
Filtering="@(new NvDatatableFilteringConfig<FilterState>
{
FilterState = filterState,
OnFilterChange = newFilter => filterState = newFilter ?? new FilterState(),
GlobalFilterFn = CustomFilterFunction
})">
<FilteringTemplate Context="api">
<div style="margin-bottom: 16px;">
<!-- Filter Controls -->
<div style="display: flex; gap: 16px; margin-bottom: 12px;">
<input
type="text"
placeholder="Search..."
value="@filterState.SearchTerm"
@oninput="@((ChangeEventArgs e) =>
filterState = filterState with { SearchTerm = e.Value?.ToString() ?? "" })"
style="padding: 8px; flex: 1;" />
<select
value="@filterState.Status"
@onchange="@((ChangeEventArgs e) =>
filterState = filterState with { Status = e.Value?.ToString() ?? "" })"
style="padding: 8px;">
<option value="">All Statuses</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select>
</div>
<!-- Active Filter Chips -->
@if (HasActiveFilters)
{
<div style="display: flex; align-items: center; gap: 8px; margin-bottom: 12px;">
<span style="font-size: 14px; font-weight: 500;">Filters applied:</span>
@if (!string.IsNullOrWhiteSpace(filterState.Status))
{
<NvBadge
Label="@($"Status: {filterState.Status}")"
Color="information"
Dismissible="true"
CloseClicked="@(() => filterState = filterState with { Status = "" })" />
}
@if (!string.IsNullOrWhiteSpace(filterState.Department))
{
<NvBadge
Label="@($"Department: {filterState.Department}")"
Color="information"
Dismissible="true"
CloseClicked="@(() => filterState = filterState with { Department = "" })" />
}
<NvButton @onclick="ClearAllFilters" Emphasis="low">
Clear all filters
</NvButton>
</div>
}
<!-- Results Count -->
<div style="font-size: 14px;">
Showing <strong>@api.FilteredRows</strong> of <strong>@api.TotalRows</strong> results
</div>
</div>
</FilteringTemplate>
</NvDatatable>
@code {
private record FilterState(string SearchTerm = "", string Status = "", string Department = "");
private FilterState filterState = new();
private bool HasActiveFilters =>
!string.IsNullOrWhiteSpace(filterState.SearchTerm) ||
!string.IsNullOrWhiteSpace(filterState.Status) ||
!string.IsNullOrWhiteSpace(filterState.Department);
private void ClearAllFilters()
{
filterState = new FilterState();
}
}
Filtering Configuration Reference
Global Filtering Config (Filtering parameter):
The filtering configuration is generic with the TFilterState type parameter, providing compile-time type safety:
public class NvDatatableFilteringConfig<TFilterState> where TFilterState : class
{
public TFilterState? FilterState { get; set; } // Strongly-typed filter state
public Action<TFilterState?>? OnFilterChange { get; set; } // Type-safe callback
// Client-side specific (default mode or Mode="NvDatatableMode.Client")
public Func<Dictionary<string, object?>, string, TFilterState?, bool>? GlobalFilterFn { get; set; }
public int DebounceMs { get; set; } // Default: 300ms
}
Note: The filtering Mode property has been removed. Filtering behavior is derived from the top-level Mode parameter on NvDatatable. For server-side filtering, set Mode="NvDatatableMode.Server" on the component.
Using the Generic Type:
When using NvDatatable with filtering, specify the type parameter on NvDatatableFilteringConfig<T>:
@* Define your filter state type *@
@code {
private record InvoiceFilter(string SearchTerm = "", string Status = "", decimal MinAmount = 0);
private InvoiceFilter filterState = new();
}
@* Specify the type parameter on the filtering config, not the component *@
<NvDatatable Columns="@columns"
Rows="@data"
Filtering="@(new NvDatatableFilteringConfig<InvoiceFilter>
{
FilterState = filterState,
OnFilterChange = HandleFilterChange, // Receives InvoiceFilter?, not object?
GlobalFilterFn = MyFilterFunction // Third param is InvoiceFilter?, not object?
})" />
@code {
// Type-safe callback - no casting needed!
private void HandleFilterChange(InvoiceFilter? newFilter)
{
filterState = newFilter ?? new InvoiceFilter();
StateHasChanged();
}
// Type-safe filter function - IntelliSense works on filter parameter!
private bool MyFilterFunction(Dictionary<string, object?> row, string columnId, InvoiceFilter? filter)
{
if (filter == null) return true;
// Direct access to filter.SearchTerm, filter.Status, filter.MinAmount - no casting!
if (!string.IsNullOrWhiteSpace(filter.SearchTerm))
{
var invoiceNumber = row["InvoiceNumber"]?.ToString()?.ToLower() ?? "";
if (!invoiceNumber.Contains(filter.SearchTerm.ToLower()))
return false;
}
return true;
}
}
⚠️ Migration Note: If you have existing code using the old non-generic approach (with object? types and casting), update your code to:
- Update
NvDatatableFilteringConfigtoNvDatatableFilteringConfig<YourFilterType> - Update your
OnFilterChangecallback signature fromAction<object?>toAction<YourFilterType?> - Update your
GlobalFilterFnto acceptYourFilterType?instead ofobject?
GlobalFilterFn Signature:
// Strongly-typed filter function
Func<Dictionary<string, object?>, string, TFilterState?, bool>? GlobalFilterFn
The function receives:
row: The complete row object with access to all fieldscolumnId: The column ID being filtered (often ignored for global filters)filterValue: Your currentFilterStatevalue - now strongly typed!
Return true to include the row, false to filter it out.
Filtering API Reference
The <FilteringTemplate> child content receives an API object with these properties:
public class NvDatatableRenderFilteringAPI
{
public int TotalRows { get; set; } // Total row count before filtering
public int FilteredRows { get; set; } // Row count after filtering
}
Best Practices
When to Use Client vs Server Filtering:
- Client-side: Datasets under a few thousand rows, instant feedback desired, all data available
- Server-side: Large datasets (10,000+ rows), filtered data must come from database, need server-side validation
Debouncing Search Inputs:
Filtering = new NvDatatableFilteringConfig<string>
{
FilterState = searchTerm,
DebounceMs = 300, // Wait 300ms after typing stops before filtering
}
This prevents excessive filtering on every keystroke, improving performance.
Resetting Pagination: Always reset to page 1 when filters change to avoid showing empty results:
private void HandleFilterChange(object? newFilter)
{
filterState = (FilterState)newFilter!;
currentPage = 0; // Reset to first page
_ = FetchData();
}
Combining with Pagination and Sorting: Filtering works seamlessly with both pagination and sorting:
- Client-side: All three operations happen in the browser on the full dataset
- Server-side: Send filter, pagination, and sort parameters together in API request
Type Safety: Define a strict record or class for your filter state for better type checking:
private record FilterState(
string SearchTerm = "",
string Status = "",
DateTime? DateFrom = null,
DateTime? DateTo = null
);
Row Selection
NvDatatable supports both single and multiple row selection with checkbox UI, persistent selection across pagination, and automatic deselection of filtered-out rows.
Configuration
Row selection is configured through the Selection parameter using NvDatatableSelectionConfig:
| Property | Type | Description |
|---|---|---|
Mode | NvDatatableSelectionMode | Selection mode: None, Single, or Multiple (default: None) |
GetRowId | Func<Dictionary<string, object?>, string?> | Required function to extract unique row identifier |
SelectedRowIds | HashSet<string>? | Currently selected row IDs (controlled state — see Controlled vs Uncontrolled Selection) |
InitialSelectedRowIds | HashSet<string>? | Seeds selection on first render only (uncontrolled). Ignored when SelectedRowIds is set. |
OnSelectionChange | Action<HashSet<string>?>? | Callback when selection changes |
EnableSelectAll | bool | Enable select all checkbox in header (only for Multiple mode, default: true) |
DeselectOnFilter | bool | Deselect filtered-out rows (default: true) |
CheckboxColumnWidth | int | Checkbox column width in pixels (default: 48) |
Basic Single Row Selection
In single selection mode, only one row can be selected at a time. Selecting a new row automatically deselects the previously selected row.
<NvDatatable Columns="@columns"
Rows="@employeeData"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Single,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); }
})" />
@code {
private HashSet<string> selectedIds = new();
}
Multiple Row Selection
In multiple selection mode, users can select multiple rows using checkboxes. A header checkbox allows selecting or deselecting all visible rows.
<NvDatatable Columns="@columns"
Rows="@employeeData"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); },
EnableSelectAll = true
})" />
@code {
private HashSet<string> selectedIds = new();
}
Row Click Actions
Use the OnRowClick callback to react to full-row clicks (for example: open a detail pane, navigate, or show actions).
The callback receives NvDatatableRowClickEventArgs with:
Row: Full row dictionary dataRowIndex: Zero-based index in the currently visible table rowsRowId: Row identifier whenSelection.GetRowIdis configured
<NvDatatable Columns="@columns"
Rows="@employeeData"
OnRowClick="HandleRowClick"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? ""
})" />
@code {
private void HandleRowClick(NvDatatableRowClickEventArgs args)
{
var rowId = args.RowId ?? "unknown";
Console.WriteLine($"Clicked row index {args.RowIndex}, id {rowId}");
}
}
Important: Selection checkbox clicks do not trigger OnRowClick, so row actions and checkbox selection remain independent.
Selection with Pagination
Selection persists across pagination - selected rows remain selected even when navigating between pages. This works for both client-side and server-side pagination.
<NvDatatable Columns="@columns"
Rows="@largeDataset"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); }
})"
Pagination="@(new NvDatatablePaginationConfig
{
InitialPageSize = 10
})" />
@code {
private HashSet<string> selectedIds = new();
// selectedIds will contain IDs from all pages
private int SelectedCount => selectedIds.Count;
}
Selection with Filtering
By default, when a row is filtered out (no longer visible due to filtering), it's automatically deselected. This behavior can be controlled with the DeselectOnFilter property.
Default Behavior (deselect filtered-out rows):
<NvDatatable Columns="@columns"
Rows="@employeeData"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); },
DeselectOnFilter = true // default
})"
Filtering="@filteringConfig" />
Keep Selection Regardless of Filtering:
<NvDatatable Columns="@columns"
Rows="@employeeData"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); },
DeselectOnFilter = false // keep filtered-out rows selected
})"
Filtering="@filteringConfig" />
Controlled vs Uncontrolled Selection
NvDatatableSelectionConfig supports two modes, mirroring the Sorting API:
- Controlled — set
SelectedRowIds(and usuallyOnSelectionChange). The parent owns the truth: the component re-syncs fromSelectedRowIdson every render. If you only need to read selections later, prefer the uncontrolled mode below — controlled state is easy to break (see the warning). - Uncontrolled — set
InitialSelectedRowIdsinstead. The component owns the state internally; users select rows freely and you read the result viaGetSelectedRows()(or theOnSelectionChangecallback) when you need it.
⚠️ Controlled-state pitfall. Because the component re-syncs internal selection from
SelectedRowIdson every render, the reference you put on the config must always reflect the latest selection. The two safe patterns are:
- Build the config inline in the markup so a fresh
NvDatatableSelectionConfig(with the up-to-dateSelectedRowIds) is constructed on every render. This is what the storybook examples do.- Cache the config in a field, but mutate the same
HashSetin place inOnSelectionChange— never reassign the parent-owned field while the config still points at the oldHashSet.Reassigning a parent-owned field while the cached config keeps the old reference will silently clear selection on the next render. If you don't actually need controlled state, use
InitialSelectedRowIdsinstead and avoid the issue entirely.
Getting Selected Row Data (Uncontrolled)
When you only need to read the selection at a specific moment (e.g. on a button click), use InitialSelectedRowIds and read selections via GetSelectedRows(). No state management, no controlled-state pitfalls:
<NvDatatable @ref="datatableRef"
Columns="@columns"
Rows="@employeeData"
Selection="@selectionConfig" />
<NvButton @onclick="ProcessSelectedRows">Process Selected</NvButton>
@code {
private NvDatatable? datatableRef;
private NvDatatableSelectionConfig selectionConfig = new()
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
InitialSelectedRowIds = new HashSet<string>() // optional — empty by default
};
private void ProcessSelectedRows()
{
if (datatableRef == null) return;
var selectedRows = datatableRef.GetSelectedRows();
foreach (var row in selectedRows)
{
var name = row["Name"]?.ToString();
var email = row["Email"]?.ToString();
// Process row data...
}
}
}
Getting Selected Row Data (Controlled)
If you also want to render something based on selection between clicks (e.g. a counter, a list of selected items), use controlled state and mutate the HashSet in place:
<NvDatatable @ref="datatableRef"
Columns="@columns"
Rows="@employeeData"
Selection="@selectionConfig" />
<p>@selectedIds.Count selected</p>
<NvButton @onclick="ProcessSelectedRows">Process Selected</NvButton>
@code {
private NvDatatable? datatableRef;
private HashSet<string> selectedIds = new();
private NvDatatableSelectionConfig selectionConfig = default!;
protected override void OnInitialized()
{
selectionConfig = new()
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids =>
{
// Mutate the existing HashSet — do NOT reassign selectedIds.
selectedIds.Clear();
if (ids != null)
{
foreach (var id in ids) selectedIds.Add(id);
}
StateHasChanged();
}
};
}
private void ProcessSelectedRows()
{
var selectedRows = datatableRef?.GetSelectedRows() ?? new();
// Process row data...
}
}
Display Selected Items
Show the currently selected items to users:
<div class="mb-4">
<h4 class="font-semibold">Selected Items (@selectedIds.Count):</h4>
@if (selectedIds.Any())
{
<ul class="list-disc ml-5">
@foreach (var id in selectedIds)
{
var row = employeeData.FirstOrDefault(r => r["Id"]?.ToString() == id);
<li>@row?["Name"]</li>
}
</ul>
}
else
{
<p class="text-gray-500">No items selected</p>
}
</div>
<NvDatatable Columns="@columns"
Rows="@employeeData"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); }
})" />
@code {
private HashSet<string> selectedIds = new();
}
Customizing Checkbox Column
Adjust the width of the checkbox column:
<NvDatatable Columns="@columns"
Rows="@employeeData"
Selection="@(new NvDatatableSelectionConfig
{
Mode = NvDatatableSelectionMode.Multiple,
GetRowId = row => row["Id"]?.ToString() ?? "",
SelectedRowIds = selectedIds,
OnSelectionChange = ids => { selectedIds = ids ?? new HashSet<string>(); StateHasChanged(); },
CheckboxColumnWidth = 60 // default is 48
})" />
Important Notes
- GetRowId is Required: You must provide a function to extract a unique identifier from each row. This is used to track selection across pagination and filtering.
// Good: Using a unique ID field
GetRowId = row => row["Id"]?.ToString() ?? ""
// Bad: Using non-unique fields
GetRowId = row => row["Name"]?.ToString() ?? "" // Names may not be unique!
-
Performance with Large Datasets: Selection state is maintained in memory as a
HashSet<string>. For very large datasets (10,000+ rows), consider implementing a server-side selection mechanism. -
Selection State Management: The component expects controlled state - you manage the
SelectedRowIdsHashSet and receive updates viaOnSelectionChange. -
Validation: If
GetRowIdis not provided when selection mode is notNone, an exception will be thrown during initialization. -
Hydration Visibility:
NvDatatableadds thehydratedhost class by default to avoid temporary hidden rendering before web component hydration completes. You can opt out by settingEnsureHydratedClass="false".
<NvDatatable Columns="@columns"
Rows="@rows"
EnsureHydratedClass="false" />
Best Practices
- Accessibility: Provide meaningful
HeaderNamevalues for screen readers - Responsive Design: Set appropriate column widths and consider hiding non-essential columns on mobile
- User Experience: Use consistent styling patterns across custom cell renderers
- Data Validation: Always handle null/undefined values in custom renderers
- Interactivity: For buttons in cells, use appropriate emphasis levels (typically 'low' for table actions)
- Performance: For large datasets (>1000 rows), use server-side or infinite scroll pagination
- State Management: When using server-side pagination, ensure proper loading states to prevent UI flickering