Blazor Routing and Navigation
This tutorial guides you through the powerful routing and navigation capabilities of Blazor applications. Learn how to define routes, navigate between components, and pass parameters.
Understanding Blazor Routing
Blazor uses a simple yet effective routing mechanism based on attributes. Each component that can be displayed directly via a URL must have the @page
directive with a specified route template.
Basic Routing
To make a component routable, add the @page
directive at the top of your .razor
file:
@page "/about"
<h1>About Us</h1>
<p>Information about our company.</p>
This component will be accessible at the URL /about
in your application.
Route Templates
Route templates allow you to define flexible URLs, including parameters. Parameters are enclosed in curly braces {}
.
@page "/products/{id}"
<h1>Product Details</h1>
<p>Displaying product with ID: @Id</p>
@code {
[Parameter]
public string Id { get; set; }
}
In this example, a URL like /products/123
will match this route, and the value 123
will be bound to the Id
parameter.
Navigating Between Pages
Blazor provides a declarative way to create navigation links using the NavLink
component. It automatically adds an "active" CSS class when the link matches the current URL, which is very useful for styling navigation menus.
Using NavLink
The NavLink
component renders as an <a>
tag but adds routing intelligence.
<NavLink href="/dashboard">
<span class="oi oi-dashboard" aria-hidden="true"></span> Dashboard
</NavLink>
<NavLink href="/settings" Match="NavLinkMatch.All">
<span class="oi oi-cog" aria-hidden="true"></span> Settings
</NavLink>
The Match
parameter controls how the link matches the current URL. NavLinkMatch.All
(default) requires an exact match, while NavLinkMatch.Prefix
matches if the link's href is a prefix of the current URL.
Programmatic Navigation
You can also navigate programmatically using the NavigationManager
service. Inject it into your component and call its NavigateTo
method.
@inject NavigationManager NavigationManager
<button @onclick="GoToContactPage">Contact Us</button>
@code {
private void GoToContactPage()
{
NavigationManager.NavigateTo("/contact");
}
}
Route Parameters and Query Strings
Route Parameters
As shown earlier, route parameters are defined in the route template and bound to component properties using the [Parameter]
attribute.
For example, to access route data:
@page "/users/{UserId:int}"
<h2>User Profile</h2>
<p>Showing profile for user ID: @UserId</p>
@code {
[Parameter]
public int UserId { get; set; }
}
Here, {UserId:int}
specifies that the parameter named UserId
must be an integer. Blazor will perform the type conversion automatically.
Query Strings
Query strings are used to pass optional data. They are accessed via the NavigationManager
's Uri
property.
@page "/search"
@inject NavigationManager NavigationManager
@implements IDisposable
<h2>Search Results</h2>
<p>Search term: @SearchTerm</p>
<p>Category: @Category</p>
@code {
private string _searchTerm;
private string _category;
public string SearchTerm
{
get
{
if (string.IsNullOrEmpty(_searchTerm))
{
var uri = new Uri(NavigationManager.Uri);
var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);
_searchTerm = queryParams["q"];
}
return _searchTerm;
}
}
public string Category
{
get
{
if (string.IsNullOrEmpty(_category))
{
var uri = new Uri(NavigationManager.Uri);
var queryParams = System.Web.HttpUtility.ParseQueryString(uri.Query);
_category = queryParams["category"];
}
return _category;
}
}
public void Dispose()
{
// Clean up if necessary, though query params are usually read-only on load.
}
}
A URL like /search?q=blazor&category=web
would populate the SearchTerm
and Category
properties.
Microsoft.AspNetCore.WebUtilities.QueryHelpers
class for more robust handling.
Layouts and Routing
You can associate components with specific layouts using the @layout
directive. This is useful for consistent page structures.
@page "/dashboard"
@layout MainLayout
<h1>Dashboard</h1>
<p>Welcome to your dashboard!</p>
Conclusion
Blazor's routing system is designed to be intuitive and powerful, allowing for clean URLs, easy navigation, and flexible parameter handling. By mastering these concepts, you can build sophisticated single-page applications with Blazor.