【问题标题】:Redirecting in blazor with parameter使用参数在 blazor 中重定向
【发布时间】:2019-06-15 15:18:57
【问题描述】:

您好,如何通过参数重定向到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 页面,并为其提供一个字符串作为参数。

【问题讨论】:

    标签: c# routing blazor


    【解决方案1】:

    这样做:

    • 创建一个 home.cshtml 文件页面,如下所示: 请注意,由于尚不支持可选参数,因此使用了两个 @page 指令。 第一个允许导航到没有参数的组件。第二个@page 指令 接受 {username} 路由参数并将值分配给 Username 属性。

    页面/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); 
            }
        }
    

    希望这会有所帮助...

    【讨论】:

    • 如何提取home页面中的参数username
    • 你不要自己解压。如您所见,home 组件包含一个名为 Username 的属性,并使用 Parameter 属性进行注释。此属性的提取和分配由 Blazor... 框架自动完成
    • 哦,我明白了,非常感谢。但是如果我想要对象,它仍然可以工作吗(如果我 stringify 他们)?
    • 如果您将对象序列化(将其转换为 JSON 字符串),我想它会起作用,但这是一个非常糟糕的主意。根据您构建应用程序的方式,您可以使用事件来通知对象某事的发生,例如验证用户凭据,并将这些凭据传递给该对象等...
    【解决方案2】:

    目前只能在 URL 中传递参数。

    因此,如果您的 home 组件需要 [Parameter] string Name,则您需要提供一个 URL 为 /home/fred,并且 fred 将被传递到 home 组件的 Name 参数中。

    如果您希望传递更复杂的数据,那么您将不得不考虑通过某种服务来实现。

    这里是路由参数官方文档的链接:https://blazor.net/docs/routing.html#route-parameters

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 1970-01-01
      • 2017-02-24
      • 2015-06-16
      • 2015-07-08
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      相关资源
      最近更新 更多