使用参数在 blazor 中重定向
Redirecting in blazor with parameter
您好,如何使用参数重定向到 Blazor
中的另一个页面?
@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
}
}
在这种情况下,我想导航到 /home
页面,给它一个字符串作为参数。
目前只能在URL中传递参数。
因此,如果您的主组件需要 [Parameter] string Name
,您需要提供 /home/fred
的 URL,并且 fred
将被传递到 Name
home组件的参数。
如果您希望传递更复杂的数据,则必须考虑通过某种服务来实现。
这里是link关于路由参数的官方文档:https://blazor.net/docs/routing.html#route-parameters
这样做:
- 像这样创建一个 home.cshtml 文件页面:
请注意,由于尚不支持可选参数,因此使用了两个 @page 指令。
第一个允许在没有参数的情况下导航到组件。第二个@page 指令
采用 {username} 路由参数并将值分配给用户名 属性.
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; };
}
- 在您的 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);
}
}
希望这对您有所帮助...
您好,如何使用参数重定向到 Blazor
中的另一个页面?
@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
}
}
在这种情况下,我想导航到 /home
页面,给它一个字符串作为参数。
目前只能在URL中传递参数。
因此,如果您的主组件需要 [Parameter] string Name
,您需要提供 /home/fred
的 URL,并且 fred
将被传递到 Name
home组件的参数。
如果您希望传递更复杂的数据,则必须考虑通过某种服务来实现。
这里是link关于路由参数的官方文档:https://blazor.net/docs/routing.html#route-parameters
这样做:
- 像这样创建一个 home.cshtml 文件页面: 请注意,由于尚不支持可选参数,因此使用了两个 @page 指令。 第一个允许在没有参数的情况下导航到组件。第二个@page 指令 采用 {username} 路由参数并将值分配给用户名 属性.
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; };
}
- 在您的 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);
}
}
希望这对您有所帮助...