Course contentsShow
← C#
Lesson 1392 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

Deep Linking and State Capture

Ensure URLs accurately represent the internal state of highly dynamic page views.

In this lesson, you will learn how to synchronize your application’s complex internal state with the browser's URL so that users can bookmark or share specific, highly dynamic views.

The Problem: State Volatility

In a modern Blazor application, a user might interact with several filters, a specific page of a data grid, and an open modal—all without changing the "page" in the traditional sense. If the user refreshes the browser, that UI state is typically lost because the URL remains static (e.g., /dashboard). Deep linking solves this by encoding your application's "view model" directly into the navigation structure.

Capturing State in the URL

To achieve persistent deep linking, you must treat the URL as the "source of truth" for your page state. Instead of keeping a list of filters in a private field, you map those parameters to query strings or route segments.

Consider a component that filters a product catalog. Instead of storing the SelectedCategory only in a variable, you sync it with the NavigationManager:

@inject NavigationManager Nav

private async Task ApplyFilter(string category)
{
    // Update the URL to reflect state
    var newUrl = Nav.GetUriWithQueryParameter("category", category);
    Nav.NavigateTo(newUrl);
}

protected override void OnInitialized()
{
    // Capture the state from the URL on load or refresh
    var uri = Nav.ToAbsoluteUri(Nav.Uri);
    if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("category", out var cat))
    {
        SelectedCategory = cat;
        // Trigger logic to load filtered data
    }
}

Why this matters

By treating the URL as an extension of your global state, you gain two major advantages:

  1. Shareability: A user can copy their browser link and send it to a colleague, who will see the exact same filters, sorting, and pagination applied.
  2. Back-Button Support: Users expect the "Back" button to undo their last action. By updating the URL on state changes, you ensure that the browser's history stack remains in sync with the user's journey through your application.

Key Takeaway: Always reflect high-level UI state in the URL using query parameters or route segments to enable seamless deep linking and robust browser history navigation.