Exploring NavigationManager in Blazor: Navigating to Components and Pages

Introduction

Are you tired of wandering and navigating through your Blazor app like a lost tourist? Fear not; in this article, we'll explore NavigationManager in Blazor, which provides a simple and efficient way to navigate to different components and web pages. We'll cover the basics of navigating to a URL and then dive into more advanced features, such as navigating to a component, reloading the page, and replacing the current URL in the browser's history. By the end of this article, you'll have a solid understanding of how to use NavigationManager in your Blazor app.

What is navigation anyway?

Navigation is the process of moving between different pages or parts of a website. It can be achieved by using links, buttons, or other UI elements to redirect users to different sections of the website. Navigation is a fundamental part of the user experience, allowing users to quickly and easily find the information or functionality they need.

What is NavigationManager?

NavigationManager is a service in Blazor that provides a way to navigate between pages within a Blazor application. It uses the browser's history API to track the user's navigation history and allows you to navigate between pages using relative or absolute URLs.

To use NavigationManager, you must first inject it into your component or service. You can do this by using the @inject directive.

@inject NavigationManager NavigationManager;
  • Relative URL: A relative URL is relative to the current page's URL. For example, if the current page's URL is https://www.mywebsite.com/, then to navigate to the about page of this website, you just need "../about" This will redirect you to https://www.mywebsite.com/about.
    // Navigate to a relative URL
    NavigationManager.NavigateTo("/about");
  • Absolute URL: This is a complete URL that includes the protocol, domain, and path. For example, to reach about page from the previous example, you need the complete URL https://www.mywebsite.com/about.
    // Navigate to an absolute URL
    NavigationManager.NavigateTo("https://www.mywebsite.com/about");

 Class NavigationManager is packed with lots of features. However, we are interested in the following property, event, and methods.

  • Uri: A property that gets or sets the current URI. Always represented as an absolute URI in string form.
    // Get the current URI
    string uri = NavigationManager.Uri;
    
    // Set the current URI
    NavigationManager.Uri = "/about";
  • LocationChanged: An event that fires when the navigation location has changed.
    protected override void OnInitialized()
    {
        //Subscribing to an event
        NavigationManager.LocationChanged += OnLocationChanged;
    }
    
    private void OnLocationChanged(object sender, LocationChangedEventArgs e)
    {
        // Do something
    }

We have 3 overloaded methods available to navigate to a specified URI.

  1. NavigateTo(string uri, bool forceLoad): forceLoad is used to bypass client-side routing and forces the browser to load the new page from the server.
  2. NavigateTo(string uri, bool forceLoad = false, bool replace = false): replace parameter replaces the current entry in the history stack if set to true. If false, then it appends the new entry to the history stack.
  3. NavigateTo(string uri, NavigationOptions options): Takes an enum parameter called "NavigationOptions" which includes the values "ForceLoad" and "ReplaceHistoryEntry".

The forceload forces Blazor to create a new instance of the component instead of reusing an existing instance. This can be useful when you need to ensure that the initialization logic is executed every time the page is navigated to.

Blazor server comes with two default components, FetchData.razor, and Counter.razor, which we will use to demonstrate the NavigateTo() method. Here is how the output of the FetchData.razor component looks out of the box. It retrieves and displays weather forecast data.

NavigationManager in Blazor

 Here is the code for the Counter component; I have added four extra buttons and their corresponding methods invoked when each button is clicked.

@page "/counter"
@inject NavigationManager NavigationManager
<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
&nbsp;
<button class="btn btn-primary" @onclick="NavigateToRelativeURL">Relative</button>
&nbsp;
<button class="btn btn-primary" @onclick="NavigateToAbsoluteURL">Absolute</button>
&nbsp;
<button class="btn btn-primary" @onclick="NavigateWithForceLoad">Force load</button>
&nbsp;
<button class="btn btn-primary" @onclick="NavigateWithReplaceHistory">Replace history</button>


@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    private void NavigateToRelativeURL()
    {
       NavigationManager.NavigateTo("/fetchdata");
    }

    private void NavigateToAbsoluteURL()
    {
        NavigationManager.NavigateTo("https://www.c-sharpcorner.com/members/rikam-palkar");
    }

    private void NavigateWithForceLoad()
    {
        NavigationManager.NavigateTo("/fetchdata", true);
    }

    private void NavigateWithReplaceHistory()
    {
        NavigationManager.NavigateTo("/fetchdata", true, true);
    }
}

Listing 2: Counter.razor

The following gif is the demonstration of the output of listing 2.

NavigationManager in Blazor

Conclusion

With NavigationManager, developers can create responsive web apps that seamlessly navigate between different parts of the application. We saw how to use the NavigateTo() method to navigate to a component and various parameters to make the most of navigation in Blazor.


Similar Articles