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

Advanced Client Side Routing

Implement custom logic for handling query parameters and complex route data mapping.

Mastering Advanced Query Parameter Mapping

In this lesson, you will learn how to move beyond simple route templates to implement custom logic that transforms complex URL query parameters into strongly-typed objects for your Blazor components.

Beyond Basic Route Parameters

While simple routes like /product/{Id} are standard, real-world applications often rely on query strings—such as /search?category=electronics&sort=price_desc&page=2. Relying on manual string parsing inside your OnInitialized method becomes messy and error-prone as requirements grow.

Instead, we can use a Parameter Mapper pattern. By leveraging the [SupplyParameterFromQuery] attribute combined with private setters or custom property logic, we can sanitize and map incoming data before the component renders.

Implementation Pattern

Consider a search page where you need to interpret complex filtering criteria. Rather than mapping every single query key individually, you can use a private method to synchronize state:

@page "/search"

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

    [SupplyParameterFromQuery]
    public int? Page { get; set; }

    // Custom logic to handle complex filtering mapping
    private SearchFilter _filter = new();

    protected override void OnParametersSet()
    {
        // Transform loose query params into a complex domain object
        _filter = new SearchFilter 
        {
            Category = Category ?? "All",
            PageNumber = Page ?? 1,
            IsDefault = string.IsNullOrEmpty(Category)
        };
    }
}

By intercepting the parameter lifecycle via OnParametersSet, you decouple the URL structure from your component’s internal logic. This allows you to handle edge cases—like default values, range validation, or mapping an "array" query parameter (e.g., ?tags=csharp,blazor)—without polluting your UI logic.

This approach ensures that your component always operates on a valid, strongly-typed object regardless of how malformed or incomplete the incoming browser URL might be. It keeps your routing intent separated from your business logic, making your frontend far more resilient to changing URL schemes.

Key Takeaway: Use the OnParametersSet lifecycle hook to translate raw, nullable query parameters into refined, strongly-typed objects, ensuring your components remain robust against unpredictable URL input.