Blazor Routing

This tutorial explores how to implement routing in your Blazor applications, allowing users to navigate between different pages and content within your single-page application.

Understanding Blazor Routing

Blazor applications, by default, are Single Page Applications (SPAs). Routing in Blazor is declarative and based on the @page directive in Razor components. When a component has the @page directive, it becomes a routable component.

The @page Directive

The @page directive specifies the URL that the component should respond to. You can specify multiple routes for a single component.

@page "/counter"
@page "/count"

Counter

Current count: @currentCount

@code { private int currentCount = 0; private void IncrementCount() { currentCount++; } }

Example Output (when navigating to /counter or /count):

A simple counter component will be displayed with a current count and a button to increment it.

Route Parameters

You can define routes that accept parameters. These parameters are passed to your component and can be accessed directly by properties marked with the [Parameter] attribute and matching the route segment name.

Defining Routes with Parameters

Use curly braces { } to define route parameters.

@page "/users/{userId:int}"

User Profile

Displaying profile for User ID: @UserId

@code { [Parameter] public int UserId { get; set; } }

In this example:

Navigating with Parameters

You can navigate to these parameterized routes using the NavLink component or programmatically using the NavigationManager.

Using NavLink:

<NavLink href="/users/123">View User 123</NavLink>

Programmatically:

@inject NavigationManager NavigationManager

<button @onclick="GoToUserProfile">Go to User Profile 456</button>

@code {
    private void GoToUserProfile()
    {
        NavigationManager.NavigateTo("/users/456");
    }
}

Optional Routes and Catch-all Routes

Blazor also supports optional route parameters and catch-all routes.

Optional Parameters

Mark a route parameter with a question mark ? to make it optional. The corresponding property should be nullable.

@page "/products"
@page "/products/{category:alpha?}"

Product List

@if (string.IsNullOrEmpty(Category)) {

All Products

} else {

Products in category: @Category

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

This component can be accessed at /products or /products/electronics (or any other alpha string).

Catch-all Routes

A catch-all route uses { ... } to capture the rest of the URL path.

@page "/{**path}"

Page Not Found

The requested path was: @Path

@code { [Parameter] public string? Path { get; set; } }

This route should typically be placed last in your component's routing definitions to act as a fallback for unmatched URLs.

The NavLink Component

The NavLink component is a special component that renders an <a> tag but also handles active styling. When the href of a NavLink matches the current URL, it automatically adds an "active" class (or a custom class you specify).

<NavLink href="/" Match="NavLinkMatch.All">Home</NavLink>
<NavLink href="/counter">Counter</NavLink>

The Match attribute can be set to:

By understanding and leveraging Blazor's routing capabilities, you can create dynamic and user-friendly web applications with seamless navigation.