Lesson 6 of 10
Routing, Route Parameters, and Navigation
Create routable pages, use route parameters, add NavLink navigation, and navigate from C#.
Routing connects URLs to Razor components. Blazor pages use the @page directive to declare routes and can accept values directly from the URL.
1. Create a route
@page "/courses"
<h1>Courses</h1>
<p>This page is available at /courses.</p>
2. Add a route parameter
Create StudentDetails.razor:
@page "/student/{Id:int}"
<h1>Student Details</h1>
<p>Student ID: @Id</p>
@code {
[Parameter]
public int Id { get; set; }
}
Now browse to /student/12. The value 12 is assigned to the Id parameter.
3. Add links with NavLink
<NavLink href="/courses">Courses</NavLink>
<NavLink href="/student/12">Student 12</NavLink>
NavLink is useful for navigation menus because it can apply an active CSS class when its destination matches the current URL.
4. Navigate from C#
@inject NavigationManager Navigation
<button class="btn btn-primary" @onclick="OpenStudent">
Open Student 25
</button>
@code {
private void OpenStudent()
{
Navigation.NavigateTo("/student/25");
}
}
Try it yourself
Create a page that accepts a course name from the route, for example /course/blazor, and displays the supplied value.