Blazor routing and Navigation

Routing

If you take a look at the generated pages for a Blazor application, you’ll see the following

@page "/counter"

this denotes a route to our page, i.e. http://localhost:44319/counter.

Note: When you compile your application a file is generated (see Counter.g.cs in compiled folder) and this page declaration is converted to a RouteAttribute.

You can have multiple routes pointing to the same page, in this example all these routes will navigate to the same Counter.razor page

@page "/counter"
@page "/mycounter"
@page "/something"

Probably more useful is the ability to add parameters to our routes, for example

@page "/counter"
@page "/counter/{InitialValue}"

By default InitialValue is of type string, but we can change this by using a constraint, for example

@page "/counter"
@page "/counter/{InitialValue:int}"

Now we simply create a property in our code with the ParameterAttribute applied to it, like this

[Parameter]
public int? InitialValue { get; set; }

We use a nullable int in case the value is missing. We can also have routes handling different type contraints (for example a string or on int) to mean two different things

@page "/counter"
@page "/counter/{InitialValue:int}"
@page "/counter/{SomeString}"

In our OnInitialized() method (part of the component life cycle) we might then set the currentCount to InitialValue.

The routes are declared in our pages but the routing component itself can be found in App.razor. In this case the Router will locate the routes from the supplied AppAssembly

<Router AppAssembly="@typeof(Program).Assembly">

We can also includes routes within AdditionalAssemblies, for example maybe you’ve got some reusable components with routing supplied, hence we write

<Router AppAssembly="@typeof(Program).Assembly" 
   AdditionalAssemblies="new[] { typeof(MyComponents).Assembly }>

Navigation

If you want to navigate to other pages, we need to use the NavigationManager. This needs to be injected into our page, using

@inject NavigationManager NavManager

Now to navigate, for example when a button is click, we use the following

NavManager.NavigateTo("counter/2");

In the instance we’ll navigate to the relative URL/page with “counter/someData”.

This works fine when navigating to other pages but if we want to navigate within a page and we’re using the component’s OnInitialized method to initialize data?

Because OnInitialized is called when the page is initial loaded and because we’re already in the page, this method will not normally be called again if we navigate within the page, so we simply need to supply an extra parameter to our NavigateTo code to force the page to reload, i.e.

NavManager.NavigateTo("counter/2", true);

Note: An alternative solution ofcourse is to override the other life cycle method OnParameterSet and instead move initialization code to that method.