Live Chat Icon For mobile
Live Chat Icon

Blazor FAQ

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

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

Share with

Share on twitter
Share on facebook
Share on linkedin

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

Please submit your question and answer.