Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 41 ยท Routing and Layouts

Query Strings and URL State

Keep filters, sorting and paging in the Blazor URL with SupplyParameterFromQuery, GetUriWithQueryParameter and typed parsing, so pages can be shared, bookmarked and reloaded.

Route parameters identify which thing a page shows (/products/42). The query string carries the optional extras: ?category=books&sort=price&page=3. Search boxes, filters, sort order and paging belong there, because a URL that contains the state can be bookmarked, shared in a chat, reloaded and navigated with the Back button. State that lives only in a component's fields disappears on refresh.

This lesson shows how to read query values into component parameters, how to update the URL when a filter changes, and how to build safe URLs. The Razor snippets are the real syntax; the runnable code is a stand-in parser and binder in plain C#.

Reading query values

Add [SupplyParameterFromQuery] to a [Parameter] property. The framework fills it from the query string and updates it again whenever the query changes.

RAZOR
@page "/products"

<h1>Products</h1>
<p>Category: @Category, page @Page, sort: @(Sort ?? "default")</p>

@code {
    [Parameter, SupplyParameterFromQuery]
    public string? Category { get; set; }

    [Parameter, SupplyParameterFromQuery(Name = "p")]
    public int Page { get; set; } = 1;

    [Parameter, SupplyParameterFromQuery]
    public string? Sort { get; set; }
}

Facts to remember:

  • Names match case-insensitively; Name = "p" renames the key.
  • Supported types include string, int, long, bool, double, decimal, DateTime, DateOnly, TimeOnly, Guid and their nullable forms, plus arrays and List<T> for repeated keys like ?tag=a&tag=b. Enums are not supported: take a string and parse it yourself.
  • A missing key keeps the property's initializer value, so the = 1 above gives page 1 by default.
  • A value that cannot be converted (?p=abc) is treated as missing rather than throwing.
  • The attribute works on components routed by the router; for other components, read from NavigationManager directly.

Because query changes call OnParametersSet just like route changes, load data there, as taught in Routing and Route Parameters.

What the binder does

Underneath, the query string is split on &, each piece on =, and both sides are URL-decoded (+ and %20 mean a space). The stand-in below parses a query and "binds" it into a model with reflection and a custom attribute, so you can see the full path from text to typed properties.

C# Stand-in query binder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Changing the URL from code

When the user picks a filter, update the URL rather than only a field. NavigationManager.GetUriWithQueryParameter returns the current URL with one key set (or removed when you pass null), and NavigateTo moves there.

RAZOR
@inject NavigationManager Nav

<select @onchange="OnSortChanged">
    <option value="price">Price</option>
    <option value="name">Name</option>
</select>

@code {
    private void OnSortChanged(ChangeEventArgs e)
    {
        var url = Nav.GetUriWithQueryParameter("sort", (string?)e.Value);
        Nav.NavigateTo(url);          // the page parameters update automatically
    }
}

The overload with a dictionary, GetUriWithQueryParameters(Dictionary<string, object?>), changes several keys at once, for example resetting page to null whenever a filter changes (otherwise the user could end up on page 9 of a list that now has two pages).

For a search box, do not navigate on every keystroke: that spams the history. Use NavigateTo(url, replace: true) or debounce the input.

Building a URL yourself

Whenever a value comes from a user, escape it. The stand-in below builds query strings with Uri.EscapeDataString, drops empty values and keeps a stable key order.

C# Building query strings safely

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Query string or route parameter?

Use a route parameter when... Use a query value when...
it identifies the resource (/orders/17) it filters, sorts or pages a list
the page makes no sense without it the page works with a default
search engines should index each value variants should not be separate pages

Do not put secrets (tokens, passwords) in a URL: URLs end up in logs, history and referrer headers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a [SupplyParameterFromQuery] int property when the URL has ?page=abc?

    Values that cannot be converted are ignored, so the property keeps whatever default you gave it.
  2. 2. How is a repeated key such as ?tag=a&tag=b read?

    Array and List<T> parameters collect all values of a repeated key.
  3. 3. Why reset the page number when a filter changes?

    A new filter usually shrinks the result set; sending the user to page 1 avoids an empty page.
  4. 4. Which is the correct way to put user text into a URL?

    Escaping stops characters such as & and # from changing the structure of the URL.

Summary

  • Query strings hold optional state (filters, sort, page) so URLs stay shareable and reloadable.
  • [Parameter, SupplyParameterFromQuery] binds and refreshes values; unconvertible values are ignored.
  • GetUriWithQueryParameter(s) plus NavigateTo changes the URL; use replace: true for rapid updates.
  • Always escape user text, and keep secrets out of URLs.
  • Route values identify the resource; query values refine the view.

Next: Route Constraints and Catch-All Routes