Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (158).NET Core  (28).NET MAUI  (44)Angular  (65)ASP.NET  (50)ASP.NET Core  (77)ASP.NET MVC  (88)Azure  (32)Blazor  (141)DocIO  (23)Essential JS 2  (80)Essential Studio  (171)File Formats  (26)Flutter  (121)JavaScript  (170)Microsoft  (112)PDF  (65)React  (51)Succinctly series  (126)Syncfusion  (570)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (35)Webinar  (30)Windows Forms  (58)WinUI  (43)WPF  (134)Xamarin  (149)XlsIO  (25)Other CategoriesBarcode  (5)BI  (29)Bold BI  (4)Build conference  (6)Business intelligence  (53)Button  (4)C#  (117)Chart  (56)Cloud  (11)Company  (445)Dashboard  (7)Data Science  (3)Data Validation  (6)DataGrid  (54)Development  (351)Doc  (7)DockingManager  (1)eBook  (95)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (23)Extensions  (17)File Manager  (4)Gantt  (11)Gauge  (9)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (289)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (29)Performance  (9)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (7)Road Map  (10)Scheduler  (36)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (21)Solution Services  (2)Spreadsheet  (11)SQL  (8)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (89)UI  (200)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (23)Visual Studio Code  (14)Web  (323)What's new  (192)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
Blazor Router: An Overview

Blazor Routing: An Overview

Routing is a pattern-matching process that observes incoming client requests and decides what to do with each request. It refers to how we set up navigation and handle the application URL.

Like other SPA frameworks, Blazor has a router that manages virtual navigation. In addition, the Blazor server and WebAssembly apps allow routing with the help of various built-in components and services. So, in this article, I’ll go over all you need to know about routing in Blazor apps.

Router component in Blazor

Routing exists in Blazor to ensure that each request is directed to the best component with all the data necessary to display exactly what the user wants.

The Router component is used as a part of the App component in Blazor apps. The default implementation looks like this.

<Router AppAssembly="@typeof(Program).Assembly">
  <Found Context="routeData"><RouteView RouteData="@routeData"DefaultLayout="@typeof(MainLayout)"/>
  </Found>
  <NotFound>
    <LayoutView Layout="@typeof(MainLayout)">
       <p>Routing in Blazor Application.</p>
    </LayoutView>
  </NotFound>
</Router>

The AppAssembly defines which components to load for a given route. Looking at the code, we can spot two scenarios handled by Found and NotFound parameters, respectively:

  • The component with the given route is found.
  • The component with the given route is not found.

In the first case, when the component with the given route is found, the app will use the Found segment. After that, the RouteView component does all the magic for us. It receives the route data from the Router component, along with any parameters, and renders the required component together with its layout. It will use the default layout if the component doesn’t have a layout. We can set the default layout with the DefaultLayout property in the RouteView component.

In the second case, when the component with the given route is not found, the app will use the NotFound template. By default, it shows the p tag located within the LayoutView component, with a simple message informing the user that the desired page was not found. The LayoutView ensures that the specific layout gets rendered for the not found route. We can control which layout will be used by setting the Layout property of the component.

@page directive in Blazor routing

Routing rules are essential in Blazor routing since they let us define the exact component that should appear for a specified URL. We can set up these rules using the @page directive followed by the route itself.

For example, a component with the following declared code will load using the Router component if we make a request for example.com/profile.

@page "/profile"

You can also define multiple route templates using multiple @page directives like in the following example. These routes should start with the / sign. Otherwise, the app will report an error.

@page "/profile"
@page "/myprofile"

If we navigate to the route (/profile), the given route will be matched by the Router component. Then, the profile.razor page component will be rendered.

These components have a particular folder within our app folder structures, usually the Pages folder. The assembly will be scanned at the app startup to find any components with the @page directive applied.

Route parameters and constraints

It is common to use the route parameters to pass data from one page to another. After defining the Router component, it can automatically populate the corresponding component property with the same name since they are case insensitive.

For example, we should define the route parameter salary in the following code segment (wrapped with curly braces {}) and a related property that must match the route parameter’s value, @countsalary. It can automatically populate the value of the route parameter.

@page "/profile/{salary}"

<h1>@Salary</h1>
<p>monthly salary: @countSalary </p>
<button class="btn btn-primary" @onclick="IncrementSalary">see my profile </button>  

@code {
      private int countSalary = 50000;
      [Parameter]
      public string Salary { get; set; }
      private void IncrementSalary(){
          countSalary ++;
      }
}

Then, you can run the app and enter any string in the address bar after /salary/ to see the route parameter value displayed.

monthly salary: 50000

Moreover, it is also possible to limit the salary parameter to accept only integer values.

@page "/profile/{salary:int}"

...

@code {
   [Parameter]
   public string Salary { get; set; }
}

Handling navigation

The NavLink component and the NavigationManager class are the two techniques for navigating among pages.

Navigation manager

In the C# code, we can use the NavigationManager class to manage URIs and navigation. It has the following properties, methods, and events:

  • Properties: BaseUri, Uri
  • Methods: NavigateTo, ToAbsoluteUri, ToBaseRelativePath
  • Events: LocationChanged

Let’s see their work using the following example. You can create a new Blazor component and inject the NavigationManager service using the @inject directive.

@page "/profile"
@inject NavigationManager nvm

<h3>Handling Navigation</h3>
<br />

<p>Absolute URI @nvm.Uri</p>
<p>Base URI: @nvm.BaseUri</p>

Then, check for the Uri and BaseUri values. The Uri property returns the page’s current absolute URI, while the BaseUri property returns the base URI.

Handling Navigation

http://localhost:5000/profile
http://localhost:5000/

NavLink component

If you don’t want to handle navigation programmatically and instead want to generate HTML hyperlinks, you can use the NavLink component. When the link’s href attribute matches the current URL, the NavLink component toggles an active CSS class, much like the HTML <a> element.

You can make it clear to the user which navigation link is for the current page by styling the active class. We have to use the NavLink component only for the navigation menu and not for links within the page’s content. The component has a Match property that NavLink uses to configure the match options. There are two possibilities:

NavLinkMatch.All

The NavLink component will only be active if it matches the URL.

<NavLink class="nav-link" href="Profile"><span aria-hidden="true"></span> 
 Profile
</NavLink>

NavLinkMatch.Prefix

The NavLink component will be active whenever it matches any prefix of the current URL.

<NavLink class="nav-link" href="Profile" Match="NavLinkMatch.All"> 
  <span aria-hidden="true"></span> Profile
</NavLink>

As an example, consider the link <NavLink href=”Profile” Match=”NavLinkMatch.Prefix”>. While we have http://www.myprofile.com/profile for any location within the given URL, that link will be active.

Conclusion

This article covered routing features available in Blazor apps and various routing-related components and services available for developers. I hope my suggestions will help you define routes, parameters, and constraints easier than before.

Thank you for reading!

Syncfusion’s Blazor component suite offers over 70 UI components that work with both server-side and client-side (WebAssembly) hosting models seamlessly. Use them to build marvelous apps!

For questions, you can contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top