NavigationManager.NavigateTo in razor pages c# sometimes don't work

Viewed 10284

i've a very simple question about asp.net core and razor pages.

Inside c# razor code I want to redirect to another route in certain cases. If there's an async (awaiting) webservice call before, NavigationManager.NavigateTo doesn't work correctly, but no exception is thrown either.

async Task Cancel()
{
    var authState = await authenticationStateTask;
    var user = authState.User;
    if (user.Identity.IsAuthenticated){           
       // if there's some async webservice call action here, 
       // NavigationManager.NavigateTo does neither work nor an exception is thrown
       NavigationManager.NavigateTo("/Project", true);
    }
}

Do you have any idea what could be the cause?

What are the alternatives to NavigationManager.NavigateTo?

P.S. Please don't propose Response.Redirect in that way (because, that's not suitable for me).

var context = new Microsoft.AspNetCore.Http.HttpContextAccessor();
context.HttpContext.Response.Redirect("/Project", true)

Kind regards, -he.

3 Answers

Bug is already fixed now.

The problem with NavigationManager.NavigateTo(...) occurred only, because I used a button inside a posting form in my Razor page. Replaced form tag with div and now everything works fine.

Kind regards, -he

<div>
<p>
    <label>Project name: @projectName</label>
</p>
<p>
    <!-- [...] -->
    <span class="btn-cancel">
        <button class="btn-primary" @onclick="@(async () => await Cancel())">Cancel</button>
    </span>
</p></div>

@code {
    // ...
    async Task Cancel()
    {
        // here're other async action calls
        NavigationManager.NavigateTo("/Project", true);
    }
}

Another possible solution is using <form @onsubmit="Cancel"> with a <button type="submit">. This preserves advantages of forms, for example the handling of the enter-key.

little late here, but thought to share my case here. For me, NavigationManager.NavigateTo() was not working for some of the target blazor components even though they were simple components with only HTML contents like below, without any C# code in it.

@page "/unauthorized"

<h3>You are not authorized.</h3>

I noticed that "Build Action" property of the components which are not working here aren't set as "Content". So once I made this property as "Content", it started working.

enter image description here

Related