Tech News

What is Routing in Blazor?

Pinterest LinkedIn Tumblr

What is Routing in Blazor

Being an open-source and easy-to-use framework, Blazor provides impeccable ways for creating web applications using Html, C#, and extended tools. There has been considerable hype about this client-side UI framework just because of features like forms, validations, server-side rendering, routing, dependency injection, Data binding and event calling in blazor, etc. Here, in this blog, we will learn about the process of Routing in Blazor in detail.

What is Routing?

The routing is a key aspect of any web application. It is the mechanism that ensures that the client has reached the appropriate part of the request code that is written to handle that request. In other words, we can say that routing is the process by which requests are routed in the relevant code as defined in the route.

Routing is a prerequisite for every project that a developer must incorporate and maintain. Routing is easy to use, and methodology is consistence in many development frameworks. However, every framework implements routing differently and some are tedious to work with.

The Blazor Server application uses ASP.NET Core endpoint routing. Used to MapBlazorHub extension method of endpoint routing, ASP.NET Core begins to accept incoming attachments for Blazor component. The Blazor client application provides client-side routing. The router is configured in the Blazor client application in the App.cshtml file.

Blazor Client App

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

Blazor Server application

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

{

if (env.IsDevelopment())

{

app.UseDeveloperExceptionPage();

}

else

{

app.UseExceptionHandler(“/Error”);

 

app.UseHsts();

}

 

app.UseHttpsRedirection();

app.UseStaticFiles();

 

app.UseRouting();

 

app.UseEndpoints(endpoints =>

{

endpoints.MapBlazorHub();

endpoints.MapFallbackToPage(“/_Host”);

});

}

The Blazor Server application allows you to set the fallback route. It works with low priority in routing matching. The fallback route is only considered when other routes do not match. The fallback route is usually defined in the _Host.cshtml component.

@page directive

Using the @page directive, you can define routing in the Blazor component. The @page directories are converted to internal RouteAttribute when templates are compiled.

@page “/route1”

In Blazor, the part can have multiple routes. If we need that component to be able to render with multiple root values, we need to define all routes with multiple @page directives.

@page “/multiple”
@page “/multiple1”

If you have defined a class only component, you can use RouteAttribute.

using Microsoft.AspNetCore.Components;

namespace BlazorServerApp.Pages

{

public class ClassOnlyComponent: ComponentBase

{

.………

.………

}

}

Route Template

The router mechanism allows routing to be determined for each component. The route template is defined in the App.razor file. Here, we can define the layout page and default route data.

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

<Found Context=”routeData”>

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

</Found>

<NotFound>

<LayoutView Layout=”@typeof(MainLayout)”>

<p> Sorry, nothing at this address.</p>

</LayoutView>

</NotFound>

</Router>

In the above code, three components are defined under the router component: Found, NotFound, and RouteView. The RouteView component retrieves route data and the default layout. The Blazor routing mechanism renders the Found component, if a path matches, the NotFound component renders. The NotFound component allows us to provide a custom message when we can’t find routes or content.

Handle Parameter in Route Template

The route may have parameters. The parameters can be defined using curly braces inside the routing template in either @page directory or a RouteAttribute. Root parameters are automatically tied to component parameters by matching the name. This matching case is sensitive.

<h2>Route Constraint Example</h2>

@page “/routepara/{DisplayName}”

 

<h3>Name : @DisplayName</h3>

 

@code {

public string DisplayName{ get; set; }

}

The current version of the Blazor doesn’t support the optional parameter, thus you want to pass the parameter in the above example.

Route constraints

Blazor routing also allows route constraints. It applies type matching between route parameters and route data. The current version of Blazor supports is route constraints but might supports many more route constraints in the future.

<h2>Route Example</h2>

@page “/routecons/{Id:guid}”

 

<h3>Id : @Id </h3>

 

@code {

public Guid? Id { get; set; }

}

The following route barriers are supported by the Blazor

Constraint Invariant culture matching Example
int Yes {id:int}
long Yes {id:long}
float Yes {mrp:float}
double Yes {mrp:double}
decimal Yes {mrp:decimal}
guid No {id:guid}
bool No {enabled:bool}
datetime Yes {birthdate:datetime}

 

NavLink Component

Blazer provides the NavLink component that generates the HTML hyperlink element and handles the active CSS class toggle based on NavLink component href match with the current URL.

There are two options for assigning a match attribute to a NavLink component

  • All: Activates when it matches the entire current URL
  • Prefix: It is the default option. It is activated when it matches any prefix of the current URL

The NavLink component renders an anchor tag. you’ll include a target attribute.

Programmatically navigate from one component to another

Blazor are also allowed to navigate from one component to another using the program Microsoft.AspNetCore.Components.NavigationManager. The Navigation Manager service provides the following events and properties.

Event / Method Description
NavigateTo It navigates to the required URI. It takes parameter “forceload”, if its parameter is ready to true, client-side routing is bypassed and also the browser is forced to load a new page
ToAbsoluteUri It converts the respective URI into a complete URI
 NotifyLocationChanged This event is automatically fired when the browser is relocated
EnsureInitialized This method allows the acquired class to be lazy self-starting
Initialize Sets the base URI and current URI before this method is used.
NavigateToCore Navigate to the specified URI. This is an abstract method so it must be implemented in a derived class

 

Properties      Description
BasicUri Get and set the current base URI. Allows it to be presented as a complete URI ending with a slash.
Uri Get and set current URI. Allows it to be presented as a complete URI.

 

 

To navigate the URI using the NavigationManager service, you must inject the service using the @inject directive into the component. Using the NavigateTo method, you’ll navigate from one component to another component.

@page “/navexample”

@inject NavigationManager UriHelper

<h2>Navigation Example</h2>

Navigate to another component <a href=”” @onclick=”NavigatetoNextComponent”>Click here</a>

 

@code {

void NavigatetoNextComponent()

{

UriHelper.NavigateTo(“newcomponent”);

}

}

Conclusion

Blazor provides rich routing. The Blazor Server application uses ASP.NET Core endpoint routing. It provides all the features including route parameters and route constraints. It also provides a built-in component like NavLink that helps to create menu items. It provides built-in services that help us navigate from one component to another. However, there are some limitations such as the route parameter doesn’t support the optional parameter and it supports a limited number of route constraints. Hope you understand.

 

About Author:-

Ajay Patel is a Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. With sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop and Mobile solutions and is heading the technical department at ASP.NET Core Software Company – iFour Technolab USA. Inc

Write A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.