Blazor 可选路由参数

Pes*_*ska 6 blazor

创建新的 blazor 项目dotnet new blazor。修改Index.cshtml

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

<h1>Id = @Id</h1>

<p><a href="/">Without Id</a></p>
<p><a href="/15">With Id = 15</a></p>

@functions {
    [Parameter]
    public string Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

运行应用程序。

当我单击With Id = 15链接时,一切都按预期工作 - url 已更改,参数{Id}已分配给 value Id,一切正常。

但是当我Without Id在那之后单击链接时,url 已更改,但我的 Id 保持不变 - 等于 15。

为什么我的值没有改变?我在这里缺少什么?我怎样才能解决这个问题?

Dha*_*tle 18

从 ASP.NET Core 5.0 开始支持可选路由参数。

例如:

@page "/RouteParameter/{text?}"

<h1>Blazor is @Text!</h1>

@code {
    [Parameter]
    public string Text { get; set; }

    protected override void OnInitialized()
    {
        Text = Text ?? "fantastic";
    }
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 0

简单的修复方法是删除第一条路线。它让路由器忽略您的(丢失的)参数。然后使用以下命令将 Id 设为可选?

@page "/" -- remove this line
@page "/{Id?}"
Run Code Online (Sandbox Code Playgroud)

Id现在,当某些东西不存在时,它总是会被分配给, null 。