Blazor Routing
Routing in Blazor enables users to navigate to different pages or components within your single-page application (SPA). Blazor provides a flexible and powerful routing system that allows you to define navigation pathways based on URLs.
How Blazing Fast Routing Works
Blazor routing is based on convention and configuration. By default, Blazor uses the page
directive in Razor components to define their associated URL routes. Components with a @page
directive can be navigated to directly from a browser's address bar.
Defining Routes
To make a Razor component navigable, add the @page
directive at the top of the file:
@page "/products"
<h3>Product List</h3>
<p>This is the product listing page.</p>
This makes the component accessible at the /products
URL.
Route Parameters
You can define routes with parameters to capture dynamic parts of a URL. Parameters are specified within curly braces {}
in the @page
directive.
@page "/product/{id:int}"
<h3>Product Details</h3>
<p>Product ID: @Id</p>
@code {
[Parameter]
public int Id { get; set; }
}
In this example:
{id:int}
defines a parameter namedid
that must be an integer.- The parameter value is automatically bound to the component's
Id
property, which is decorated with the[Parameter]
attribute.
Parameter Constraints
You can specify constraints for route parameters to enforce type checking or specific formats:
:int
: Integer:long
: Long integer:guid
: GUID:alpha
: Alphabetic characters:regex(pattern)
: Matches a regular expression pattern
Optional Parameters
Optional route parameters can be specified by appending a question mark ?
to the parameter name and making the corresponding component property nullable.
@page "/search"
@page "/search/{query?}"
<h3>Search Results</h3>
<p>Search Query: @(string.IsNullOrEmpty(Query) ? "N/A" : Query)</p>
@code {
[Parameter]
public string? Query { get; set; }
}
This allows navigation to both /search
and /search/some_text
.
Navigation
You can use the NavLink
component for client-side navigation. NavLink
automatically adds an "active" class to the link when the current route matches the link's URL, which is useful for styling navigation menus.
<ul>
<li><NavLink href="/" Match="NavLinkMatch.All">Home</NavLink></li>
<li><NavLink href="/products">Products</NavLink></li>
<li><NavLink href="/contact">Contact</NavLink></li>
</ul>
The Match
attribute on NavLink
controls how the current URL is compared to the link's URL:
NavLinkMatch.All
: Requires an exact URL match.NavLinkMatch.Prefix
: Requires the URL to start with the specified path (default).
Programmatic Navigation
For programmatic navigation, inject the NavigationManager
service and use its NavigateTo
method.
@inject NavigationManager NavigationManager
<button class="btn btn-primary" @onclick="GoToProductPage">View First Product</button>
@code {
private void GoToProductPage()
{
NavigationManager.NavigateTo("/product/1");
}
}
Layouts and Routing
Components can be associated with layouts to provide consistent UI elements like headers, footers, and navigation bars across multiple pages. The LayoutAttribute
is used to specify a layout for a component.
@layout MainLayout
@page "/about"
<h3>About Us</h3>
<p>Information about our company.</p>
Note:
The @layout
directive should appear before the @page
directive.
Catch-all Routes
You can define a catch-all route to handle any URLs that don't match other defined routes. This is typically done using a wildcard character (*
).
@page "/{**slug}"
<h3>Not Found</h3>
<p>The requested path '@Slug' was not found.</p>
@code {
[Parameter]
public string? Slug { get; set; }
}
This component will be rendered for any URL that doesn't have a specific route defined. It's often used to display a "404 Not Found" page.
Key Takeaways:
- Use
@page
to define navigable routes. - Use curly braces
{}
for route parameters and specify constraints (e.g.,:int
). - Use
NavLink
for declarative navigation and active link styling. - Inject
NavigationManager
for programmatic navigation. - Use
@layout
to apply layouts to components. - Use catch-all routes (
/{**slug}
) for handling unknown URLs.