Routing & Navigation
7 min read
🧭 Routing & Navigation
Welcome back, coder! 🖐️
If you’ve been following along, you likely have a bunch of Blazor components sitting around. Maybe a Counter, a FetchData component, or a "Hello World" card. But right now, they are like islands in an ocean—isolated and hard to reach.
In a traditional web application, clicking a link asks the server for a brand new HTML file. The screen goes white for a second, the browser spins, and poof—new page.
But Blazor is a Single Page Application (SPA).
Definition: Client-side Routing is the process of intercepting the browser's navigation event, stopping the request to the server, and instead swapping out the visible UI component locally.
Imagine your house. 🏠
- Traditional Web: To go from the Kitchen to the Bedroom, you have to demolish the house and rebuild it with the Bedroom furniture.
- Blazor (SPA): You stay in the same house; you just swap the fridge for a bed instantly.
Let's learn how to become the architect of this magic house.
1. The @page Directive: Turning Components into Pages
🧐 The Concept
In Blazor, a "Page" is just a Component that has a URL address. Technically, there is no structural difference between a reusable button component and a full-blown "Contact Us" page. The only difference is that the page is routable.
🚧 The Problem
You have a component called UserProfile.razor. How does the browser know that when the user types https://myapp.com/profile, it should show that specific component and not the 404 error screen?
Without a map, your application is just a pile of code that no one can find.
💡 The Solution
We use the @page directive. This acts like a sticky note on your component telling the Blazor Router: "Hey! If someone asks for /profile, I’m the one you’re looking for!"
🛠️ Hands-on Implementation
Open any .razor component (or create UserProfile.razor) and add this at the very top (line 1):
@page "/profile"
<h3>User Profile</h3>
<p>Welcome to the profile area.</p>What happens under the hood?
When your app starts, the <Router> component (usually found in App.razor) scans your entire code assembly. It looks for any class marked with the [Route] attribute (which is what @page compiles down to). It builds a "Route Table" in memory.
When you type /profile:
- The Router intercepts the URL.
- It checks its table.
- It finds
UserProfile.razor. - It renders that component inside the
<Found>layout.
⚡ Professional Tip: Multiple Routes
Did you know a single component can have multiple addresses? This is great for handling legacy URLs or aliases.
@page "/profile"
@page "/my-account"
@page "/user/me"
<h3>User Profile</h3>Now, all three URLs point to the same place. It's like having a front door, a back door, and a garage door.
2. Route Parameters: Capturing Dynamic URL Values
🧐 The Concept
Route parameters allow you to pass data into a component directly through the URL structure.
🚧 The Problem
Imagine you are building an e-commerce store with 10,000 products.
You definitely do not want to create:
Product1.razorProduct2.razor- ...
Product9999.razor
That would be a maintenance nightmare (and a very large file size). You need one template that changes content based on the ID passed to it.
💡 The Solution
We use "Route Templates" with curly braces {} to define dynamic segments.
🛠️ Hands-on Implementation
Let's modify our component to accept an ID.
Step 1: Update the @page directive
Define the parameter name inside braces.
Step 2: Create a property
Create a public property with the exact same name (case-insensitive) and decorate it with [Parameter].
@page "/product/{ProductId}"
<h3>Product Details</h3>
<p>You are viewing product ID: @ProductId</p>
@code {
[Parameter]
public string? ProductId { get; set; }
}Now, if you visit /product/55, the screen will say: "You are viewing product ID: 55".
🛡️ Industry Standard: Route Constraints
In the real world, you want to be strict. What if someone types /product/banana? If your code expects a number to look up a database, your app might crash.
You can force the URL to match a specific data type using : syntax.
@page "/order/{OrderId:int}"
@page "/user/{UserId:guid}"/order/123-> Matches ✅/order/abc-> "Sorry, there's nothing at this address" (404) ❌
Common Constraints:
:int:long:guid:bool:datetime
Fun Fact: If you don't use constraints, Blazor treats everything as a
string. You'll spend half your life writingint.Parse()inside yourOnInitializedmethod. Use constraints. Save your sanity. 🧠
3. Building Menus with NavLink Components
🧐 The Concept
The NavLink component is a Blazor-specific wrapper around the standard HTML anchor (<a>) tag.
🚧 The Problem
If you use a standard HTML link like <a href="/profile">Profile</a>:
- The browser forces a request to the server.
- The entire page tears down.
- CSS and JavaScript act like they’ve never met you before.
- The app reloads.
This destroys the "Single Page App" experience. It’s slow and jarring. Also, standard links don't know if they are currently "active" (CSS styling for the selected menu item).
💡 The Solution
Use <NavLink>. It intercepts the click event (preventing the reload) and tells the Router to update the URL and switch the view internally.
It also automatically adds a CSS class called active to the link when the current URL matches the link's href.
🛠️ Hands-on Implementation
Usually found in NavMenu.razor (in the default template).
<nav>
<!-- BAD: Causes full reload -->
<a href="/">Home (Slow)</a>
<!-- GOOD: SPA Navigation -->
<NavLink class="nav-link" href="/" Match="NavLinkMatch.All">
<span class="oi oi-home" aria-hidden="true"></span> Home
</NavLink>
<NavLink class="nav-link" href="counter">
<span class="oi oi-plus" aria-hidden="true"></span> Counter
</NavLink>
</nav>🧠 Vital Concept: NavLinkMatch
Notice the Match="NavLinkMatch.All" on the Home link?
NavLinkMatch.Prefix(Default): Adds theactiveclass if the URL starts with the href.- If href is
/(Home), literally every URL starts with/. So withoutAll, your "Home" button would look selected forever, even when you are on the "Counter" page.
- If href is
NavLinkMatch.All: Adds theactiveclass only if the URL matches the entire string perfectly.
Rule of Thumb: Always use Match="NavLinkMatch.All" for your Home link (/). Use default (Prefix) for section roots (like /admin).
4. Programmatic Navigation using the NavigationManager
🧐 The Concept
Programmatic navigation is moving the user to a new page using C# code instead of waiting for them to click a link.
🚧 The Problem
Imagine a login form.
- User types username/password.
- User clicks "Login".
- Your code verifies credentials.
- Now what?
You can't ask the user to "Please click this link to go to the dashboard now that you are logged in." You need to teleport them there automatically.
💡 The Solution
Blazor provides a built-in service called NavigationManager. You inject it into your component and call its methods.
🛠️ Hands-on Implementation
Step 1: Inject the Service
Step 2: Call NavigateTo
@page "/login"
@inject NavigationManager NavManager
<h3>Login</h3>
<button class="btn btn-primary" @onclick="HandleLogin">
Log In
</button>
@code {
private void HandleLogin()
{
// 1. Perform logic (check database, etc.)
bool isValidUser = true; // Pretend this is real logic
if (isValidUser)
{
// 2. Redirect the user
NavManager.NavigateTo("/dashboard");
}
}
}🎢 Advanced Moves: Query Strings
Sometimes you need to read data like ?search=shoes from the URL. NavigationManager helps here too (specifically in .NET 6+).
@inject NavigationManager NavManager
@code {
protected override void OnInitialized()
{
// Get the URI
var uri = NavManager.ToAbsoluteUri(NavManager.Uri);
// Parse Query String (Requires Microsoft.AspNetCore.WebUtilities)
if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("search", out var searchTerm))
{
Console.WriteLine($"User searched for: {searchTerm}");
}
}
}(Note: In .NET 8, Blazor introduced [SupplyParameterFromQuery] which makes this even easier, but NavigationManager is the foundation).
⚠️ A Warning on ForceLoad
The .NavigateTo method has a second parameter: forceLoad.
NavManager.NavigateTo("/dashboard", forceLoad: true);Setting this to true bypasses Blazor routing and forces a hard browser refresh.
Use case: Only use this if you are navigating away from your Blazor app to a completely different external site, or if you need to completely reset the application state (like after a logout). Otherwise, keep it false (default) to keep the app fast.
📝 Summary Checklist
- Use
@page "/path"to make a component accessible via URL. - Use
{param}in the route to accept data, and:typeto prevent crashes. - Use
<NavLink>for menus to get that sweet "active" styling and prevent page reloads. - Use
NavigationManager.NavigateTo()inside your C# methods to redirect users after an action.
You are now the Traffic Controller of your application! 🚦 Go direct some traffic.
📚 References & Further Reading
- Official Docs - Blazor Routing: Microsoft Learn - Blazor Routing
- Official Docs - NavigationManager: Microsoft Learn - NavigationManager Class
- Route Constraints Reference: Microsoft Learn - Route Constraints
Challenge
Challenge: Create a Summation Function
Your task is to write a complete JavaScript program that defines and uses a function to add two numbers.
Requirements:
- Define a function named
calculateSum. - The function must accept two parameters, which you can name
aandb. - Inside the function, it should add the two parameters together.
- The function must return the calculated sum.
- Outside the function, declare a constant variable named
value1and assign it the number42. - Declare another constant variable named
value2and assign it the number8. - Call your
calculateSumfunction, passingvalue1andvalue2as arguments. - Store the returned value from the function call in a new constant variable named
totalSum.
Expected result
The final code should contain the following elements:
- A function declaration or expression for
calculateSumthat accepts two parameters. - Inside the function, a
returnstatement that returns the sum of the two parameters (e.g.,return a + b;). - A
constvariable namedvalue1initialized with the numerical value42. - A
constvariable namedvalue2initialized with the numerical value8. - A
constvariable namedtotalSumwhich is assigned the result of callingcalculateSum(value1, value2).