使用参数在 blazor 中重定向 [英] Redirecting in blazor with parameter

查看:28
本文介绍了使用参数在 blazor 中重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,如何使用参数重定向到 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
    }
}

在这种情况下,我想导航到 /home 页面,给它一个字符串作为参数.

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

推荐答案

这样做:

  • 像这样创建一个 home.cshtml 文件页面:请注意,由于尚不支持可选参数,因此使用了两个 @page 指令.第一个允许在没有参数的情况下导航到组件.第二个@page 指令获取 {username} 路由参数并将值分配给 Username 属性.
@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 中重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆