Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

Data access by render mode

A page that runs on the server can read your database. A page that runs in the browser can't, so it calls an API. The page's render mode decides which. If your pages load data through an interface, the same page works in both places.

One interface for every mode

Put the queries behind an interface, a store, and have the page ask it. The page doesn't know where the store gets its rows:

ICustomerStore.cs
public interface ICustomerStore
{
    Task<IReadOnlyList<CustomerRow>> ListAsync(CancellationToken cancellationToken = default);
    Task<CustomerRow?> GetAsync(int id, CancellationToken cancellationToken = default);
}

public sealed record CustomerRow(int Id, string Name, string City);
Customers.razor
@page "/customers"
@inject ICustomerStore Customers

<Table Items="_customers">
    <Columns>
        <PropertyColumn Property="c => c.Name" />
        <PropertyColumn Property="c => c.City" />
    </Columns>
</Table>

@code {
    private IReadOnlyList<CustomerRow> _customers = [];

    protected override async Task OnInitializedAsync() => _customers = await Customers.ListAsync();
}

The render mode decides which class answers. There are four render modes and two places a page runs, so there are two classes to write at most.

What each render mode needs

Render modeThe page runsWhat answers the interface
StaticOn the serverA store over your DbContext
Interactive ServerOn the server, for as long as its circuitThe same store, with a context for each call
WebAssemblyIn the browser, after prerendering on the serverA client store that calls your endpoints, and the server’s store while prerendering
AutoOn the server on the first visit, in the browser on later onesBoth stores, each registered in its own project

Which pattern an app needs

The app's pagesWhat to build
Static, Interactive Server, or bothA store over your DbContext. No API.
Mostly static, with a few pages in the browserThe same store, plus endpoints and a client store for the data those few pages use.
WebAssembly or Auto throughoutEndpoints and a client store for all of the app's data.

Use the interface in a server-only app too. To move a page to the browser later, you add a client store and its endpoints, and the page doesn't change.

Next steps

Connection lost

Rejoining the server…