skip to content

In a Blazor data grid component, how do @typeparam and RenderFragment<TItem> parameters let callers template each row, and what is the context variable?

level: middleimportance: should knowfreq 45%

answer

  1. RenderFragment versus RenderFragment<T>
  2. ChildContent is the implicit slot
  3. @typeparam TItem and type inference
  4. context, renamed with Context="order"
  5. [CascadingTypeParameter] for child columns

basics

~20 s

A grid declares @typeparam TItem and a [Parameter] RenderFragment<TItem> RowTemplate; it calls @RowTemplate(item) for each row. Callers write the template as a child element, and inside it the current item is available as context, or under a name set with the Context attribute.

solid answer

~40 s

A **templated component** takes UI as parameters. `RenderFragment` is a delegate that writes markup; `RenderFragment<TItem>` takes an argument, so a grid declared with `@typeparam TItem` can expose `[Parameter] public RenderFragment<TItem>? RowTemplate { get; set; }` and render `@RowTemplate(item)` inside its `foreach`. The caller supplies `<RowTemplate>...</RowTemplate>` as a child element; inside it the argument is named `context` by default, renamed with `Context="order"` on that element or on the grid itself, which matters when templates are nested. `TItem` is usually inferred from `Items="orders"`, or set with `TItem="WorkOrder"`. A parameter named `ChildContent` receives content placed directly inside the component without a wrapper element. Child column components can inherit `TItem` when the grid declares `[CascadingTypeParameter(nameof(TItem))]`.

code

razor · 19 lines
razor
@* MaintenanceGrid.razor *@
@typeparam TItem
@attribute [CascadingTypeParameter(nameof(TItem))]

<table>
    <thead>@HeaderTemplate</thead>
    <tbody>
        @foreach (var item in Items)
        {
            <tr @key="item">@RowTemplate(item)</tr>
        }
    </tbody>
</table>

@code {
    [Parameter, EditorRequired] public IReadOnlyList<TItem> Items { get; set; } = [];
    [Parameter] public RenderFragment? HeaderTemplate { get; set; }
    [Parameter, EditorRequired] public RenderFragment<TItem> RowTemplate { get; set; } = default!;
}

go deeper

for a junior

Know that ChildContent receives the markup between a component's tags and that a RenderFragment parameter is rendered with @ in the component.

for a middle

Explain RenderFragment<T>, @typeparam, the context variable and Context attribute, and how type inference and named template elements work.

for a senior

Design templated components that nest cleanly, use CascadingTypeParameter for column components, and account for fragments not crossing render mode boundaries or skipping re-renders.

for a principal

Decide which UI pieces a shared component library templates versus fixes, balancing flexibility for product teams against consistency and render cost.

## Render fragments in Blazor A **render fragment** is Blazor's representation of a piece of UI that can be passed around as a value: - `RenderFragment` is a delegate `void (RenderTreeBuilder builder)`; invoking it writes markup into the current render tree. - `RenderFragment<TValue>` is a delegate `RenderFragment (TValue value)`: give it an item and it returns the fragment for that item. A component that accepts fragments as `[Parameter]` properties is a **templated component**. The caller decides what each part looks like; the component decides when and how often to render it. That is the right shape for a fleet-maintenance app's reusable `MaintenanceGrid`: the grid owns paging, sorting and layout; each page decides how a work-order row or a vehicle row looks. ## Building the grid 1. `@typeparam TItem` makes the component generic, so it compiles to `MaintenanceGrid<TItem>`. 2. `[Parameter] public IReadOnlyList<TItem> Items { get; set; }` receives the data. 3. `[Parameter] public RenderFragment? HeaderTemplate { get; set; }` holds the header row. 4. `[Parameter] public RenderFragment<TItem>? RowTemplate { get; set; }` holds the per-row template. 5. The markup renders `@HeaderTemplate` once and `@RowTemplate(item)` inside `@foreach (var item in Items)`, usually with `@key="item"` on the row element. A `null` plain `RenderFragment` simply renders nothing, but a `RenderFragment<TItem>` is a delegate that must be checked for `null` before it is invoked - or marked `[EditorRequired]` when the grid makes no sense without it. ## Using it: child elements and context The caller supplies each fragment as a **child element named after the parameter**: | Caller writes | Bound to | |---|---| | `<HeaderTemplate>...</HeaderTemplate>` | `HeaderTemplate` (`RenderFragment`) | | `<RowTemplate>[email protected]...</RowTemplate>` | `RowTemplate` (`RenderFragment<TItem>`), with the item as `context` | | content placed directly between the component's tags | a parameter that must be named `ChildContent` | Inside a `RenderFragment<T>` template the argument is called **`context`** by default. The name can be changed with the `Context` attribute: - on the template element, `<RowTemplate Context="order">`, for that template only; - on the component element, `<MaintenanceGrid Context="order">`, for all its templates. Renaming becomes necessary when templated components nest - a grid row containing another templated component would otherwise have two `context` variables in scope. ## Generic type inference Usually the compiler infers `TItem` from an argument such as `Items="workOrders"`; when it cannot, the caller writes `TItem="WorkOrder"`. When the grid's columns are separate child components (`<GridColumn TItem="WorkOrder" ...>`), repeating `TItem` on every column is noisy: putting `[CascadingTypeParameter(nameof(TItem))]` on the grid (via `@attribute`) lets descendants with a type parameter of the same name infer it from the grid. ## Limits and pitfalls - A render fragment is code with a closure, not data, so it cannot cross a render mode boundary into a component with a different render mode; a templated grid and its templates must render in the same runtime. - Invoking a fragment does not create a component: the template's markup becomes part of the grid's own render output, so the grid re-renders it each time the grid renders. - Fragment-typed parameters are delegates, which Blazor's change detection cannot compare cheaply, so a parent that re-renders also re-renders the grid. - Keep sorting and selection outside the templates: the grid raises `EventCallback` parameters such as `OnSort`, and the page owns the data.

  • How would you share MaintenanceGrid across several fleet apps?
    Put it in a Razor class library: `dotnet new razorclasslib` creates a project on the `Microsoft.NET.Sdk.Razor` SDK that references `Microsoft.AspNetCore.Components.Web` and declares `<SupportedPlatform Include="browser" />` so the browser-compatibility analyzer runs. Apps reference the project or its NuGet package and add an `@using`; files in the library's `wwwroot` are served at `_content/{PackageId}/...`. Routable pages in a library also need the app's `Router` to list the assembly in `AdditionalAssemblies`.
  • Why must content placed directly inside <MaintenanceGrid> go to a parameter named ChildContent?
    ChildContent is the convention for implicit content: markup between a component's opening and closing tags that is not wrapped in an element matching another fragment parameter is assigned to a `RenderFragment` parameter named `ChildContent`. If the component has no such parameter, rendering fails with an `InvalidOperationException` saying the component type does not have a property matching the name `ChildContent`.

  • Inside a RenderFragment<TItem> template the current item is called item by default.
  • Each RowTemplate invocation creates a separate child component instance per row.
  • A RenderFragment parameter can be passed to a child with a different render mode like any other value.
  • TItem must always be written explicitly because Razor cannot infer generic component types.
  • Implicit child content binds to whichever RenderFragment parameter is declared first.