同一页面中的 Blazor 路由更改

问题描述:

我是当前设置:

  • .NET core 3(预览版 6)
  • Blazor 服务器端渲染

在 Blazor 页面中,我有如下内容:

In a Blazor page I have something like the following:

@page "/page"
@page "/page/{Id}"

与:

[Parameter]
public string Id { get; set; }

现在,例如从 /page/1 导航到 /page/2 时,我可以使用 OnParametersSetAsync 来检测这些变化.但是在从/page/1导航到/page时出现问题.OnParametersSetAsync 可以检测到此更改,但是 Id 参数将保持为之前路由中的 1.

Now, when navigating from, for example, /page/1 to /page/2, I can use OnParametersSetAsync to detect these changes. But the problem occurs when navigating from /page/1 to /page. OnParametersSetAsync can detect this change, however the Id parameter will stay as 1 from the previous route.

我想知道在这种情况下我能做什么.

I was wondering what i could do in this situation.

Blazor 不会用 null 覆盖空参数,自己做:

Blazor doesn't override empty parameters with null, do it by yourself:

@page "/Counter"
@page "/Counter/{Id}"
<h1>Current Id: @IdString;</h1>
<a href="/Counter"> go home </a> |
<a href="/Counter/1"> go home 1 </a> |
<a href="/Counter/2"> go home 2 </a>

@code
{
    private string IdString;
    [Parameter] public string Id { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        // copy par value somewhere
        IdString = Id?.ToString() ?? "";

        // rest parm (set to null) by yourself
        Id=null;  
    }
}