Blazor导航管理器:在位置更改时取消导航

9

问题:

在Blazor上有没有一种方法可以取消导航?

假设有一个简单的a href链接,像这样:

<a href="/some/other/blazor/spa/page">Go</a>

我希望取消导航(例如,如果我们正在编辑表单)。

我尝试过的方法:

通过JS

我通过JSInterop设置了onbeforeunload dom委托:

window.onbeforeunload = function(){
        return 'Vols abandonar aquesta pàgina?';
      };

但是Blazor绕过了它。

通过locationchanged

我尝试在locationchanged事件上拦截导航,但未成功:

@implements IDisposable
@inject NavigationManager NavigationManager

...

protected override void OnInitialized()
{
    NavigationManager.LocationChanged += HandleLocationChanged;
}

private void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
    // Cancel Navigation Here
}

public void Dispose()
{
    NavigationManager.LocationChanged -= HandleLocationChanged;
}
4个回答

5

目前不支持该功能,正在讨论是否在.NET V5中实现,社区已有贡献的pull-request,希望能够成功合并。 https://github.com/dotnet/aspnetcore/pull/24417

在Blazor中导航时页面不会改变,因此没有unload事件来触发onbeforeunload。


带有社区贡献的拉取请求,所以希望能够被合并进去。 - dani herrera
1
简短的更新:预计将在 .NET 6 中提供。 - JoeGER94
5
很遗憾,看起来这个问题最早要等到 .NET 7 才能解决。 - Mr.Technician
1
嗨,Peter,也许这个功能已经可用了?https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/routing?view=aspnetcore-7.0#handleprevent-location-changes - dani herrera

4

1

更新@PeterMorris的答案。

截至2021年5月17日,NavigationManger的位置更改事件现在已经提交给.NET 6.0。我希望在应用程序的全局级别上捕获此事件将成为可能。

enter image description here

https://github.com/dotnet/aspnetcore/issues/14962


1
@daniherrera 哈哈,深夜编程。现在已经修复了 :) - Ogglas

-2

你尝试过把你的js文件放在index.html或_host.cshtml页面中吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接