Blazor FAQ - Routing

Find answers for the most frequently asked questions
Expand All Collapse All

By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page.

Follow this example to achieve passing values from one page to another.
[Page1.razor]

@page "/page1"
@inject NavigationManager UriHelper

<h3>Click button to pass the value to other page.</h3>
<button class="btn btn-primary" @onclick="OnClick">Pass Value</button>

@code {

    private string parameter = "ParameterValue";
    private void OnClick()
    {
        UriHelper.NavigateTo($"counter/{parameter}");
    }
}

Get the passed Page1 parameter value in Page2.
[Page2.razor]

@page "/page2/{Value}"

<p>@Value</p>

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

}

Refer to this link for more details.

Permalink

Data is passed using ASP.NET Core Endpoint Routing for Blazor server applications. Using MapBlazorHub endpoint routing extension method, ASP.NET Core will start accepting the incoming link for Blazor component.

The route uses the parameter (page name) to navigate to the corresponding components.

In the following code example, you get the dropdown value and pass the parameter to navigate the page andthe  full details of the employee is displayed based on the employee’s value.

@inject NavigationManager UriHelper

<select @onchange="@onChange">
    <option></option>
    <option value=1>Andrew Fuller</option>
    <option value=2>Anne Dodsworth</option>
    <option value=3>Janet Leverling</option>
</select>

@code {
    private void onChange(Microsoft.AspNetCore.Components.ChangeEventArgs args)
    {
        UriHelper.NavigateTo("employeeDetails/" + args.Value);
    }
}

[EmployeeDetails.razor]

@page "/employeeDetails/{Id:int}"

@if (empData != null)
{
<div class="container">
    <div class="row details">
        <div>
            <label><b>Employee Id: </b></label>
            <span>@empData.Eid</span>
        </div>
        <div>
            <label><b>Employee Name: </b></label>
            <span>@empData.FirstName</span>
        </div>
        <div>
            <label><b>Designation: </b></label>
            <span>@empData.Designation</span>
        </div>
    </div>
</div>
}

<style>
    .details {
        display: block;
    }
</style>

@code {

    [Parameter]
    public int Id { get; set; }

    private EmployeeData empData { get; set; }

    protected override void OnInitialized()
    {
        empData = employeeData.Where(i => i.Eid.Equals(Id)).FirstOrDefault();
    }
    public class EmployeeData
        {
            public string FirstName { get; set; }
            public string Designation { get; set; }
            public int Eid { get; set; }
        }
        List<EmployeeData> employeeData = new List<EmployeeData>
        {
            new EmployeeData() { FirstName = "Andrew Fuller",  Designation = "Team Lead", Eid= 1 },
            new EmployeeData() { FirstName = "Anne Dodsworth", Designation = "Developer", Eid= 2 },
            new EmployeeData() { FirstName = "Janet Leverling", Designation = "HR", Eid= 3 },
        };
}
Permalink

Blazor provides support for passing the route parameter as DateTime format. This needs to be mentioned while defining the route parameter in the route as @page “/route/{parameter:datetime}” at the top of the .razor component file..

Refer to the following code sample.

index.razor

@page "/"

<button @onclick="CurrentTime">Current Time</button>

@code {
    public void CurrentTime()
    {
        NavManager.NavigateTo("/time/" + DateTime.Now);
    }
}

Time.razor

@page "/time/{param:datetime}"

<h3>Time</h3>
<p>@Param</p>
@code {
    [Parameter]
    public DateTime Param { get; set; }
}
Permalink

You can get the current page title in Blazor by using the “title” property of the document object in JavaScript and by using a .JavaScript interop since there is no DOM accessibility in Blazor. The following example shows how to get the page name.

[script.js]

window.getTitle = () => { 
       return document.title; 
};
@page "/"

@inject IJSRuntime jsRuntime

<h2>Page Title: @Title</h2>

<button class="btn btn-primary" @onclick="@GetTitle">Get Title</button>


@code {

    public string Title = "";
    
    public async void GetTitle()
    {
            Title = await jsRuntime.InvokeAsync<string>("getTitle");
     }
}
Permalink

A query string stores values in the URL that are visible to users. It is mostly used to pass the data from one page to another. In Blazor, the query string can be added using the NavigationManager. You can pass multiple parameters through the URL and access it via queryhelpers,

1. Install the package Microsoft.AspNetCore.WebUtilities from NuGet.

2. Use the QueryHelpers.ParseQuery.TryGetValue method

@page "/queryparam"
@inject NavigationManager navManager

<h3>Query Paramter Demo</h3>
<div>Id = @Id</div>
<div>Name = @Name</div>
@code{
 string Id { get; set; }
 string Name { get; set; }
 protected override void OnInitialized()
  {
            GetId();
            GetName();
   }
                public void GetId()
 {
        var uri = new Uri(navManager.Uri);
        Id =       Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query).TryGetValue("id", out var type) ? type.First() : "";
        }
        public void GetName()
        {
            var uri = new Uri(navManager.Uri);
            Name = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(uri.Query).TryGetValue("name", out var type) ? type.First() : "";
        }
    }
Permalink

You can redirect to a page in Blazor using the Navigation Manager’s NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.

Refer to the following code snippet.

@page "/redirect"
@inject NavigationManager NavManager

<h1>Redirect Page</h1>

<p>Redirecting to Default Page</p>

@code {
    protected override void OnInitialized()
    {
        NavManager.NavigateTo("/");
    }
}
Permalink

A URL can be opened in a new tab either by using the NavLink component or by using JavaScript. In the NavLink component, we can specify the URL to be opened in a new tab in the href parameter. In interop’s IJSRuntime instances, the method InvokeAsyncwith parameters open, URL, and _blank are used. Here, the third parameter, _blank, is used to notify that the URL needs to be opened in the new tab.

@inject IJSRuntime jsRuntime

<NavLink href="/counter">Open</NavLink> 
<button @onclick="NavigateToNewTab">New Tab Navigation</button>

@code {

    public async Task NavigateToNewTab()
    {
        string url = "/counter";
        await jsRuntime.InvokeAsync<object>("open", url, "_blank");
    }
}
Permalink

Blazor doesn’t consider the word casing and it just assigns the value if the name is matched.

@page "/RouteParameter"
@page "/RouteParameter/{name}"

<h1>Welcome to blazor : @Name !!!</h1>


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

       protected override void OnInitialized()
       {
             Name = Name ?? "David";
       }
}

The router parses the name parameter from the URL and sets the value of the component. For instance, if the URL is /RouteParameter/JonSnow, the Name property will be set to “ JonSnow “.

Permalink

You can perform routing without changing the URL with the help of NavigationManager. You need to inject NavigationManager to use this service. You can use this service to perform routing programmatically.

Service Injection

@inject NavigationManager Navigate

<button @onclick="NavigateTo">Navigate</button>

@code {

      private void NavigateTo(){
             Navigate.NavigateTo("url");//specify required url here
      }
}
Permalink

Generally, a query string stores values in a URL that are visible to users. It is mostly used to pass the data from one page to another.

In Blazor, the query string can be added using NavigationManager. To access query parameter:

  1.  Install the package Microsoft.AspNetCore.WebUtilities from NuGet.
  2. Use the QueryHelpers.ParseQuery.TryGetValue method.
@page "/queryparam"
@inject NavigationManager UriHelper

<h3>Query Paramter Demo</h3>

<button @onclick="Navigate">Click</button>

<div>Id = @Id</div>

@code {


    string Id { get; set; }

    void Navigate()
    {
        var query = new Dictionary<string, string> { { "Id", "1001" } };

        navManager.NavigateTo(QueryHelpers.AddQueryString(navManager.Uri, query));

        var uri = navManager.ToAbsoluteUri(navManager.Uri);

        if (QueryHelpers.ParseQuery(uri.Query).TryGetValue("Id", out var param))
        {
            Id = param.First();
        }
    }
}
Permalink

Inject NavigationManager in razor.

@inject NavigationManager NavigationManager

Use Uri from NavigationManager to get the current URL.

string currentUrl = NavigationManager.Uri;

Sample code

@page "/sample"
@inject NavigationManager NavigationManager

<p>@currentUrl</p>

@code {
    private string currentUrl;

    protected override void OnInitialized()
    {
        currentUrl = NavigationManager.Uri;
    }
}
Permalink

Navigating from link

There are two ways to link pages in Blazor:

  • Using Anchor: We normally use this in HTML.
  • Using NavLink: This is introduced in Blazor.
<h3>Anchor Link</h3>
<p>
    <a href="/navigate1">Navigate 1</a><br />
</p>

<h3>Nav Link</h3>
<p>
    <NavLink href="/navigate2">Navigate 2</NavLink><br />
</p>

Navigate from code

We can navigate to another component programmatically using the NavigationManager service:

  1. Inject the service @inject directive.
  2. Use the NavigateTo() method for navigation.
@page "/page1"
@inject NavigationManager UriHelper

<h3>Naviagte to another component Programatically</h3>
<button @onclick=@Navigate>Navigate</button>


@code {
void Navigate()
{
    UriHelper.NavigateTo("page2");
}
}

Permalink

A route constraint enforces type matching on a route segment to a component.

In the following example, the route to the Users component only matches if:

  • An Id route segment is present on the request URL.
  • The Id segment is an integer (int).
@page "/Route"
@page "/Route/{id:int}"

<h3>Routing Id: @Id</h3>

@code {
    [Parameter]
    public int Id { get; set; }
}

Reference link:

https://docs.microsoft.com/en-us/aspnet/core/blazor/routing?view=aspnetcore-3.1

Permalink

The parameters can be defined using curly braces within a routing template in both the @page directive and RouteAttribute.

Using @page directive

@page "/Route"
@page "/Route/{id}"

<h3>Routing Id: @Id</h3>

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

Using RouteAttribue

[Route("/Route/{id}")]
public class BaseComponent: ComponentBase
{
    public string Id { get; set; }
}

Reference link:

https://docs.microsoft.com/en-us/aspnet/core/blazor/routing?view=aspnetcore-3.1

https://www.c-sharpcorner.com/article/routing-in-blazor/

Permalink

No, the NavigateTo method in the UriHelper class of Blazor does not have built-in support for opening a URL in a new tab. It is primarily used to navigate within the same browser tab. 

To open a URL in a new tab or window, you can use JavaScript interop in Blazor. Here’s an example of how you can achieve this: 

[index.razor] 

@page "/" 
@inject IJSRuntime jsRuntime 
@inject NavigationManager uriHelper 
@using Microsoft.AspNetCore.Components 

<h1>Navigate</h1> 
<p>Enter a URL to navigate to:</p> 
<input type="text" @bind="@url" /> 
<br /> 
<label> 
    <input type="checkbox" @bind="@openInNewTab" /> 
    Open in new tab 
</label> 
<br /> 
<button @onclick="NavigateToUrl">Go</button> 

@code { 
    private string? url { get; set; } 
    private bool openInNewTab { get; set; } 
    private void NavigateToUrl () 
    { 
        if (openInNewTab) 
        { 
            jsRuntime.InvokeVoidAsync("open", url, "_blank"); 
        } 
        else 
        { 
            uriHelper.NavigateTo(url); 
        } 
    } 
} 

Refer to this thread for more information. 
 
View Sample in GitHub 

Permalink

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.