In this article, we will explore routing in Blazor,

  • In an application, it is required that users will navigate between different screens for that you need to define routing rules in an application. The routing rule helps us to define which component will appear on the screen according to the URL in which the user is located. This routing rule in Blazor is configured using the @page directive.
  • In the component, we will define page directive at the top like as shown below,

@page “/”

@page “/GetHomePage”

Here, we are specifying through which URL we are allowed to access the specific component.

  • If the user is specifying any route which is not defined in any of the components then you will end up by getting the following message,
Routing in Blazor
  • This message what you are getting is through the App.razor file was this message is defined you can replace this with Custom Not Found page.

App.razor

<Router AppAssembly=”@typeof(Program).Assembly”><Found Context=”routeData”><AuthorizeRouteView RouteData=”@routeData” DefaultLayout=”@typeof(MainLayout)” /></Found><NotFound><CascadingAuthenticationState><LayoutView Layout=”@typeof(MainLayout)”><p>Sorry, there’s nothing at this address.</p></LayoutView></CascadingAuthenticationState></NotFound></Router>
  • Till now we have seen that with the navigation menu and page directive we can navigate between different pages but sometimes you want to do navigation in code itself for that we can use navigation manager service.
@page “/”@inject NavigationManager navigationManager<div><button type=”button” @onclick=”NavToMainPage”>Navigate To Product Component</button></div>@code {private void NavToMainPage(){navigationManager.NavigateTo(“product”);}}

As you see over here we have injected NavigationManager service and we used the NavigateTo method to go on another component.

  • Parameters in a Blazor not only come from parent component but also through browser parameters which come through browsers are called route parameters,
@page “/Product/{id:int}”<h3>Parameter is — @id</h3>@code {[Parameter] public int id { get; set; }}
  • NavLink component is used to make navigation link active it will add the active class to the selected navigation menu with the NavLink component we are passing Match parameter as NavLinkMatch.All or NavLinkMatch.The prefix was NavLinkMatch.All are active when href matches completely and NavLinkMatch.Prefix it will check current route values and also we should use navlink only in case of navigation menu items.

Thank You, See you in the next article !!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *