Obtaining location information and navigating with NavigationManager

Suppose you write a component to handle a URI that the user requests, such as http://www.contoso.com/pizzas/margherita/?extratopping=pineapple.

When you write a component, you might need access to navigation information like:

  • The current full URI, such as http://www.contoso.com/pizzas/margherita?extratopping=pineapple.
  • The base URI, such as http://www.contoso.com/.
  • The base relative path, such as pizzas/margherita.
  • The query string, such as ?extratopping=pineapple.

You can use a NavigationManager object to obtain all these values. You must inject the object into the component and then you can access its properties. This code uses the NavigationManager object to obtain the website’s base URI and then uses it to set a link to the home page:

razorCopy

@page "/pizzas"
@inject NavigationManager NavManager

<h1>Buy a Pizza</h1>

<p>I want to order a: @PizzaName</p>

<a href=@HomePageURI>Home Page</a>

@code {
    [Parameter]
    public string PizzaName { get; set; }
    
    public string HomePageURI { get; set; }
    
    protected override void OnInitialized()
    {
        HomePageURI = NavManager.BaseUri;
    }
}

To access the query string, you must parse the full URI. To execute this parse, use the QueryHelpers class from the Microsoft.AspNetCore.WebUtilities assembly:

razorCopy

@page "/pizzas"
@using Microsoft.AspNetCore.WebUtilities
@inject NavigationManager NavManager

<h1>Buy a Pizza</h1>

<p>I want to order a: @PizzaName</p>

<p>I want to add this topping: @ToppingName</p>

@code {
    [Parameter]
    public string PizzaName { get; set; }
    
    private string ToppingName { get; set; }
    
    protected override void OnInitialized()
    {
        var uri = NavManager.ToAbsoluteUri(NavManager.Uri);
        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("extratopping", out var extraTopping))
        {
            ToppingName = System.Convert.ToString(extraTopping);
        }
    }
}

With the preceding component deployed, if a user requested the URI http://www.contoso.com/pizzas?extratopping=Pineapple, they would see the message “I want to add this topping: Pineapple” in the rendered page.

You can also use the NavigationManager object to send your users to another component in code by calling the NavigationManager.NavigateTo() method:

razorCopy

@page "/pizzas/{pizzaname}"
@inject NavigationManager NavManager

<h1>Buy a Pizza</h1>

<p>I want to order a: @PizzaName</p>

<button class="btn" @onclick="NavigateToPaymentPage">
    Buy this pizza!
</button>

@code {
    [Parameter]
    public string PizzaName { get; set; }
    
    private void NavigateToPaymentPage()
    {
        NavManager.NavigateTo("buypizza");
    }
}
jboss training courses malaysia

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *