Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting in blazor with parameter

Tags:

c#

routing

blazor

Hello how can you redirect to another page in Blazor with a parameter?

@page "/auth"
@using Microsoft.AspNetCore.Blazor.Services;
@inject AuthService auth
@inject IUriHelper urihelper;

<input type="text" bind="@Username" />
<button onclick="@AuthAsync">Authenticate</button>



@functions{

    public string Username { get; set; }
    public string url = "/home";

    public async Task AuthAsync()
    {
        var ticket=await this.auth.AuthenticateAsync(Username);
        urihelper.NavigateTo(url); //i see no overload that accepts parameters
    }
}

In this case i want to navigate to the /home page giving it a string as parameter.

like image 896
Bercovici Adrian Avatar asked Jan 22 '19 07:01

Bercovici Adrian


People also ask

How do you navigate to another page in Blazor with parameter?

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.

How do I redirect in Blazor?

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.

How pass multiple parameters in URL Blazor?

The easiest way is to use Route parameters instead of QueryString: @page "/navigatetopage/{id:int}/{key}" @code { [Parameter] public int Id{get;set;} [Parameter] public string Key{get;set;} ... }


1 Answers

Do this:

  • Create a home.cshtml file page like this: Note that two @page directive are employed since optional parameters are not supported yet. The first permits navigation to the component without a parameter. The second @page directive takes the {username} route parameter and assigns the value to the Username property.

Pages/home.cshtml

@page "/home"
@page "/home/{username}"

<h1>@Username is authenticated!</h1>

@functions {
    // Define a property to contain the parameter passed from the auth page
    [Parameter]
    private string Username { get; set; };
}
  • Do this in your auth.cshtml
    @functions{

        public string Username { get; set; }
        public string url = "/home";

        public async Task AuthAsync()
        {
            var ticket=await this.auth.AuthenticateAsync(Username);
            // Attach the parameter to the url
            urihelper.NavigateTo(url + "/" + Username); 
        }
    }

Hope this helps...

like image 98
enet Avatar answered Sep 19 '22 14:09

enet