Routing in Blazor

24 September 2021 at 10:00 by ParTech Media - Post a comment

We visit hundreds of websites every day to meet different purposes. For example, a banking website to perform transactions, an eCommerce website to shop, or even a streaming platform to view videos. And all of them have a myriad of features to offer the users.

For example, a banking website has a default landing page (called the home page), a section to go through the different products of the bank, a section to register and purchase the products, and so on. When you visit all these pages, you will notice that the base URL of the website remains the same.

For example, when you enter the URL https://www.partech.nl/nl/ you will be redirected to our home page. If you select an option like Contact or Vacancies, the base URL (partech.nl) remains the same. The page to which you are being redirected gets appended on top of the base URL (https://www.partech.nl/nl/contact)

This feature of redirecting users to the required page within the website is known as routing. There are hundreds of technologies with which a website can be built. Based on your choice, the way the routing is implemented will also differ. In our earlier blog, we had seen everything about Blazor. In this post, we will take it one step ahead and understand how to redirect users to different pages inside a Blazor website.

Table of contents

  1. Introduction to Route and Routing
  2. Understanding the different ways of routing in Blazor
  3. Conclusion

Introduction to Route and Routing

Routing is an important concept of every web application. It is the mechanism that ensures the loading of the right code for the request placed by the user.

Route is the URL pattern and routing is the mechanism that matches the pattern of the route and determines what's to be loaded for each request. And in Blazor, the Blazor server application uses ASP .Net Core endpoint routing (present in the C# based files) and the Blazor client application uses client-side routing (available in .cshtml pages).

In the traditional server-based applications, based on the matched route, the page is fetched from the server-side and rendered in the client. Whereas in the case of Single Page Applications(SPAs), the navigation does not happen between pages like traditional applications. Instead, we would be doing virtual navigation by modifying the content that is present in the DOM.

Blazor is also capable of doing virtual navigation similar to SPA applications with its in-built router. Let's understand it in detail in the next section.

Understanding the different ways of routing in Blazor

To understand the routing process in Blazor, we are going to create a sample application. The sample application is going to be based on the available project template - Blazor web assembly App.

Select the template, provide a valid name for the solution and also choose the required framework that needs to be used in this project.

Once the project is created, it comes with the folder structure as below.

App.razor file holds the component that handles the virtual navigation of the application. The code in the file App.razor looks like below.

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

  <Found Context="routeData">

​    <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />

  </Found>

  <NotFound>

​    <LayoutView Layout="@typeof(MainLayout)">

            <p>Sorry, there's nothing at this address.</p>

​    </LayoutView>

  </NotFound>

</Router>

In the above config, there are two elements (‘Found’ and ‘NotFound’). For the ‘Found’ scenario, Routing is achieved by sending the Appassembly to the router, which is then scanned across the pages in the application. This, in turn, will look for any component that has a name similar to the route next to the @page directive.

When we run the created razor application, the application lands in the URL https://localhost:portal. And when we select the counter option from the left side navigation panel, the URL then gets updated to https://localhost:portal/counter.

!

And if we look for the ‘counter’ component in the code, the Counter.razor file begins with the first line as

@page “/counter”.

For the ‘Not found’ scenario, if the appassembly which is sent in the route is not matching in the application, then in the main layout, the text - ‘Sorry, there's nothing at this address.’ will be displayed to the user.

To test it out, try https://localhost:portal/contactus

In case if we need to replace a component with the NotFound data, it is possible by creating a new page like ‘ErrorPage’ and create a CSS and Razor page for the same. Then replace the content inside the element section with the created error page name.

Example

<NotFound>

​    	<ErrorPage />

</NotFound>

Now if we rerun the application and go to the incorrect route page, then the below screen would be displayed.

@page directive is one of the ways to achieve routing in the Blazor application. Users can also pass route parameters in this. For example, @page ‘/counter/{counterId: int}’ can be used inside this page by referring to @counterId.

So far we have seen how to navigate to different pages using the page directive. Sometimes, it would be essential to route from the code. Here’s how to achieve that.

On the error page, we are going to add a button, which on clicking would redirect the user back to the homepage.

To achieve it, the below lines of code are used in the Errorpage.razor file.

<div class="errorPage">

  <h3>ErrorPage</h3>

    <div class="row">

        <div class="col text-md-center m-5 text-primary">

​      <button type="button" class="btn btn-primary" @onclick="ReturnToHome">Return to the Home Page</button>

​    </div>

  </div>

</div>

@code {

  [Inject]

  public NavigationManager NavigationManager { get; set; }

  public void ReturnToHome()

  {

​    NavigationManager.NavigateTo("/");

  }

}
 

There is a button component in the HTML now. On clicking the button, the method ‘ReturnToHome’ is called (which is present in the @Code section). Inside the method, the Navigation manager helps in redirecting the user back to the homepage.

Once the code is compiled, if users visit the application/obj/Debug/net5.0/Razor/Pages, they can find the converted pages which will have the corresponding route in their header. Similarly, users can navigate by specifying paths as Nav links.

Final Words

Like every other technology, all the possible ways of routing are possible in Blazor albeit with a different syntax. So go ahead and try out routing in your next Blazor application.

Latest