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.
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:
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.
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.
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" @>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: 50000Moreover, 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:
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/
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.
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 forum, support portal, or feedback portal. We are always happy to assist you!