What does the @page directive do, and how do route templates map URLs to components?
Last updated
The @page directive turns a component into a routable page by registering a route template with the Blazor router. When the URL matches the template, the router renders that component.
How it works:
At compile time
@page "/counter"adds a[Route]attribute; theRoutercomponent scans the assembly for these and matches the current URL.A component can have multiple
@pagedirectives to answer more than one URL.
Route parameters:
Curly braces capture segments:
@page "/user/{Id}"binds to a matching[Parameter]property.Add type constraints (
{Id:int}) and catch-all segments ({*path}) as needed.
Optional and query: Optional parameters use
{Id?}; query strings can be bound with[SupplyParameterFromQuery].
[lang:razor]
@page "/product/{Id:int}"
<h1>Product @Id</h1>
@code {
[Parameter] public int Id { get; set; }
}
- https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-10.0
- https://www.telerik.com/blogs/blazor-basics-blazor-routing-navigation-fundamentals
- https://blazor-university.com/routing/defining-routes/
- https://www.learnblazor.com/routing
- https://www.syncfusion.com/blogs/post/blazor-routing-an-overview