Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 41 ยท Routing and Layouts

Navigation, NavLink and NavigationManager

Move between Blazor pages with anchors, NavLink and NavigationManager. Learn base URIs, NavigateTo options, active link matching and how to guard against leaving a page.

A route table decides what a URL shows, but users also need ways to change the URL. Blazor gives you three tools: ordinary <a> links, the NavLink component that highlights the current page, and the NavigationManager service for navigating from code. Together they keep the app a single-page experience: the browser does not reload, Blazor swaps components.

This lesson explains each tool, the idea of the base URI that makes relative links work, and the events that let you react to or even cancel a navigation. As in the previous lesson, the framework code is shown read-only, and the runnable programs are plain C# stand-ins for the logic.

Blazor intercepts clicks on normal anchors that point inside your app. You do not need a special component for a basic link:

RAZOR
<a href="products/42">Product 42</a>
<a href="/about">About</a>

Internal links are handled by the client router with no page load; links to other hosts or with target="_blank" behave as usual. If you want to force a full page reload (for example to leave Blazor for a plain MVC page), add the attribute data-enhance-nav="false" for enhanced navigation or use NavigateTo(..., forceLoad: true) from code.

The base URI

Notice href="products/42" has no leading slash. It is resolved against the <base href="/" /> element in your host page. That is why a base href is required in Blazor: every relative link, every resource and the router itself depend on it. If your app is hosted in a sub-folder such as /shop/, you set <base href="/shop/" /> and all links keep working.

NavLink renders an <a> and adds the CSS class active when its href matches the current URL. Use it for menus.

RAZOR
<nav>
    <NavLink href="" Match="NavLinkMatch.All">Home</NavLink>
    <NavLink href="products">Products</NavLink>
    <NavLink href="about" ActiveClass="current">About</NavLink>
</nav>

There are two match modes:

  • NavLinkMatch.Prefix (default): active when the current path starts with the link path, on a segment boundary. products is active on /products and /products/42.
  • NavLinkMatch.All: active only when the whole path is equal. The home link needs this, otherwise "" would be a prefix of every URL and always highlighted.

The stand-in below reproduces the matching rule so you can see why Match="All" exists.

C# Stand-in NavLink matching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two details are worth noting. /productsale does not activate products, because the rule respects segment boundaries. And with Prefix, the empty home link lights up on every page, because the root path is a prefix of every URL: that is why you write Match="NavLinkMatch.All" on the home link.

Inject NavigationManager to read the current location and to navigate from code.

RAZOR
@inject NavigationManager Nav

<button @onclick="GoToCart">Checkout</button>

@code {
    private void GoToCart() => Nav.NavigateTo("cart");
}

Useful members:

Member Purpose
Uri Current absolute URL
BaseUri The base href as an absolute URL, always ends with /
NavigateTo(uri, forceLoad, replace) Navigate; forceLoad reloads the page, replace overwrites the history entry
ToAbsoluteUri(relative) Combine with the base URI
ToBaseRelativePath(absolute) Strip the base URI, giving products/42
LocationChanged Event raised after every navigation
RegisterLocationChangingHandler Run code before navigation and optionally cancel it
GetUriWithQueryParameter Build a URL with a changed query string value

replace: true is the right choice after a successful form submit: the user pressing Back should not return to the filled-in form.

Reacting to location changes

Subscribe to LocationChanged to run code on each navigation, for example analytics or closing a mobile menu. Because it is an event on a long-lived service, you must unsubscribe when the component goes away, which means implementing IDisposable:

RAZOR
@implements IDisposable
@inject NavigationManager Nav

@code {
    protected override void OnInitialized() => Nav.LocationChanged += OnChanged;

    private void OnChanged(object? sender, LocationChangedEventArgs e)
        => Console.WriteLine($"Now at {e.Location} (intercepted: {e.IsNavigationIntercepted})");

    public void Dispose() => Nav.LocationChanged -= OnChanged;
}

Forgetting the unsubscribe is a classic memory leak: the service keeps a reference to every dead component.

Preventing navigation

RegisterLocationChangingHandler lets you inspect and cancel a navigation, which is how "You have unsaved changes" prompts are built. The NavigationLock component wraps the same feature for forms. The stand-in below models the pipeline with a history stack, replace, base-relative paths and a veto handler.

C# Stand-in NavigationManager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Programmatic navigation tips

  • Use relative paths ("cart") so the app keeps working under a sub-path. A leading / is relative to the host root, which breaks sub-folder hosting.
  • Build URLs from data with Uri.EscapeDataString for each user-supplied piece.
  • For links that should open outside the app use <a href="https://..." target="_blank" rel="noopener">.
  • If a navigation starts a long operation, show a loading state: the old page stays visible until the new component renders.

Enhanced navigation (on by default in Blazor Web Apps since .NET 8) also applies to static server-rendered pages: the framework fetches the next page and patches the DOM instead of reloading, preserving scroll and focus where it can.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the Home NavLink usually use Match="NavLinkMatch.All"?

    With Prefix matching, the root path would match every page, so Home needs an exact match.
  2. 2. What does NavigateTo("thanks", replace: true) do?

    replace swaps the current history entry, so Back does not return to the page you just left.
  3. 3. A component subscribes to NavigationManager.LocationChanged. What must it also do?

    The service outlives the component, so an event handler left attached keeps the component alive.
  4. 4. Which element is required in the host page so relative links resolve correctly?

    Blazor resolves relative URLs against the base href, so it must match where the app is hosted.

Summary

  • Internal <a> links are intercepted by Blazor, so no page reload happens.
  • NavLink adds the active class; use NavLinkMatch.All for the home link.
  • NavigationManager navigates from code and exposes Uri, BaseUri and location events.
  • Unsubscribe from LocationChanged in Dispose; use a location-changing handler to guard unsaved work.
  • Prefer relative paths so the app works under any base path.

Next: Layouts and Nested Layouts