skip to content

In a Blazor Web App, how does [SupplyParameterFromQuery] bind catalog filters from the query string, and how should a page update those filters?

level: middleimportance: should knowfreq 44%

answer

  1. a cascading value supplier
  2. Name maps a different key
  3. repeated keys fill an array
  4. GetUriWithQueryParameter, null removes
  5. OnParametersSet runs, not OnInitialized

basics

~20 s

[SupplyParameterFromQuery] fills a property from the query string key of the same name, or from Name. To change a filter, build the URL with NavigationManager.GetUriWithQueryParameter(s) and call NavigateTo; the same page instance receives new values and OnParametersSet runs.

solid answer

~40 s

Mark a property `[SupplyParameterFromQuery]` (optionally `Name = "light"`); since .NET 8 it needs no `[Parameter]`, may be `private`, and works in non-routable components too. Supported types are `bool`, `DateTime`, `DateOnly`, `TimeOnly`, `decimal`, `double`, `float`, `Guid`, `int`, `long` and `string`, their nullable forms, and arrays, which repeated keys fill. Keys match case-insensitively and values parse with the invariant culture. A value that cannot be parsed, such as `?page=abc` for `int?`, throws instead of becoming `null`. To change filters, build the URL with `Navigation.GetUriWithQueryParameter("light", "shade")` or `GetUriWithQueryParameters(dict)`; a `null` value removes the key. Then call `NavigateTo`. The page stays the same instance: the query provider supplies new values, so `OnParametersSet(Async)` runs again but `OnInitialized` does not. In ASP.NET Core 10 a same-page `NavigateTo` no longer scrolls to the top.

code

razor · 20 lines
razor
@page "/catalog"
@inject NavigationManager Navigation

<button @onclick='() => SetLight("shade")'>Shade plants</button>
<button @onclick='() => SetLight(null)'>Any light</button>

@code {
    [SupplyParameterFromQuery(Name = "light")]
    private string? Light { get; set; }

    private void SetLight(string? light) =>
        Navigation.NavigateTo(
            Navigation.GetUriWithQueryParameter("light", light));

    protected override async Task OnParametersSetAsync()
    {
        // Runs on the first render and again after every query change.
        await Task.CompletedTask; // load plants for Light here
    }
}

go deeper

for a junior

Recall that [SupplyParameterFromQuery] reads a query key into a property, that Name maps a different key, and that repeated keys fill an array.

for a middle

Explain building URLs with GetUriWithQueryParameter(s), why OnParametersSetAsync runs on a query change, and which types parse, with unparseable values throwing.

for a senior

Show you would harden pages against malformed URLs, avoid redundant reloads on re-render, and keep filters shareable through the URL instead of component state.

for a principal

Discuss the URL as the contract for filter state, bookmarking and analytics, and how static SSR links and interactive updates should produce the same URLs.

## The attribute The **query string** is the part of a URL after `?`, a list of `key=value` pairs. Blazor binds it to component properties with `[SupplyParameterFromQuery]` (namespace `Microsoft.AspNetCore.Components`). The attribute derives from `CascadingParameterAttributeBase`: the values come from a framework-provided **cascading value supplier** that reads `NavigationManager.Uri`, not from the parent component. The nursery's catalog page reads three filters: ```razor @page "/catalog" @inject NavigationManager Navigation @code { [SupplyParameterFromQuery] private string? Species { get; set; } [SupplyParameterFromQuery] private int? Page { get; set; } [SupplyParameterFromQuery(Name = "light")] private string[]? Light { get; set; } } ``` For `/catalog?species=fern&page=2&light=shade&light=partial`, `Species` is `fern`, `Page` is `2` and `Light` holds both light values. ## Binding rules - **Name.** Without `Name`, the key is the property name. Keys are compared case-insensitively. - **Since .NET 8.** No `[Parameter]` is needed, the property may be `private`, and the attribute works in a component without `@page`, for example a shared filter panel. - **Types.** `bool`, `DateTime`, `DateOnly`, `TimeOnly`, `decimal`, `double`, `float`, `Guid`, `int`, `long`, `string`, the nullable forms of the value types, and arrays of any of them. Parsing uses the invariant culture. - **Missing and empty values.** A missing key gives the type's default: `null` for nullable and reference types, `0` for `int`, an empty array for arrays. An empty value such as `?page=` gives `null` for `int?`. - **Unparseable values throw.** `?page=abc` for an `int?` property raises an `InvalidOperationException` ("Cannot parse the value..."). A nullable type does not soften that. When a URL may carry junk, bind a `string` and parse it yourself. - **Unsupported types throw** too: a property of a custom type cannot be supplied from the query. ## Writing filters back into the URL `NavigationManagerExtensions` builds the new URL from the current one: | Call | Result | |---|---| | `GetUriWithQueryParameter("light", "shade")` | adds the key, or sets every existing `light` occurrence to `shade` | | `GetUriWithQueryParameter("species", (string?)null)` | removes the key | | `GetUriWithQueryParameters` with `["light"] = new[] { "shade", "sun" }` | writes the key once per array value | | `GetUriWithQueryParameters(new Dictionary<string, object?> { ... })` | several changes at once | Names and values are URL-encoded and formatted with the invariant culture. The result is a string; nothing happens until you pass it to `NavigationManager.NavigateTo`. ## What runs after the URL changes The same steps happen in an interactive page: 1. `NavigateTo` changes the URL and raises `LocationChanged`. 2. The query-string supplier sees a new query and notifies the components subscribed to it. 3. The router renders the same page type at the same place, so the **existing instance** receives new parameter values. 4. `OnParametersSet` and `OnParametersSetAsync` run again; `OnInitialized` and `OnInitializedAsync` do not. That is why a catalog that loads plants in `OnInitializedAsync` shows stale results after the first filter change. Load in `OnParametersSetAsync`, and compare the new values with the previous ones so that unrelated re-renders do not reload. Under static SSR, every filter change is a new request: an `<a>` link or a `<form method="get">` produces the new URL, and the page renders from scratch with the new values. ## Query values versus route values | | Route parameter `{Id:int}` | Query parameter `?page=2` | |---|---|---| | Declared with | `@page` template plus `[Parameter]` | `[SupplyParameterFromQuery]` alone | | Takes part in matching | yes, a constraint miss means no match | no, the route matches regardless | | Bad text | the template does not match | an `InvalidOperationException` | | Missing | the template does not match (unless optional) | the property keeps its default | | Good for | identity of the resource | filters, sorting, paging | The split is a design choice too: `/plants/12` names one plant, while `?light=shade&page=2` narrows a list that can be bookmarked and shared. ## ASP.NET Core 10 behaviour worth knowing Since .NET 10, `NavigateTo` no longer scrolls to the top of the page for a same-page navigation. Changing `?page=2` to `?page=3` keeps the viewport where it was; scroll to the top explicitly if the design needs it. ## Common mistakes - Adding `[Parameter]` as well, a .NET 6/7 habit that is no longer required and lets a parent overwrite the value. - Expecting `?page=abc` to become `null`. - Concatenating `?` and `&` by hand and forgetting to encode values. - Putting the data load in `OnInitializedAsync`.

  • Why do filter changes show stale plants when the page loads data in OnInitializedAsync?
    A query-only navigation keeps the same page instance. Blazor supplies the new query values as parameters, so `OnParametersSetAsync` runs again, but `OnInitializedAsync` ran once when the instance was created. Move the load to `OnParametersSetAsync` and skip it when the filter values did not change.
  • How do you make a catalog page tolerate a hand-edited URL like ?page=abc?
    Bind `page` to a `string?` property with `[SupplyParameterFromQuery]` and parse it with `int.TryParse` in `OnParametersSet`, falling back to page 1. An `int?` property throws an `InvalidOperationException` for text it cannot parse; nullability only covers a missing or empty value.

  • A [SupplyParameterFromQuery] property must also carry [Parameter] in .NET 8 and later
  • An unparseable value like ?page=abc binds as null on an int? property
  • GetUriWithQueryParameter navigates to the new URL by itself
  • A query-string change creates a new page instance, so OnInitializedAsync reloads the data
  • [SupplyParameterFromQuery] works only on components that declare @page in .NET 10

Assumes ASP.NET Core 10: [SupplyParameterFromQuery] has needed no [Parameter] since .NET 8, and since .NET 10 NavigateTo no longer scrolls to the top for same-page navigations such as a query-string change.