Blazor in .NET 8 introduces the option to execute on the server (so called static mode). It can accept Form POSTs which is great. But how am I supposed to navigate to another page after that? If I call NavigationManager.NavigatoTo I get Microsoft.AspNetCore.Components.NavigationException
Is there any other way to redirect the user to another page?
Some example code
namespace DemoBlazorWebApp.Client.Pages;
using DemoBlazorWebApp.Dtos;
using Microsoft.AspNetCore.Components;
public partial class ProductCreate
{
[Inject]
private NavigationManager NavigationManager { get; set; } = null!;
[SupplyParameterFromForm]
private ProductCreateDto Model { get; set; } = new();
private bool IsSaving { get; set; }
private async Task SubmitAsync()
{
IsSaving = true;
try
{
ProductDto? product = await //save the product somehow
NavigationManager.NavigateTo("/Products/" + product.ProductId);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
IsSaving = false;
}
}
}
@page "/Products/Create"
<h3>Product Create</h3>
@if (IsSaving)
{
<p>
Saving...
</p>
}
else
{
<EditForm FormName="ProductCreate" Model="@Model" OnValidSubmit="SubmitAsync">
<DataAnnotationsValidator />
<ValidationSummary />
<p>
<label>
</label>
</p>
<p>
<label>
Name:
<InputText @bind-Value="Model.Name" />
</label>
</p>
<p>
<label>
Price:
<InputNumber @bind-Value="Model.Price"></InputNumber>
</label>
</p>
<p>
<label>
Description:
<InputTextArea @bind-Value="Model.Description" />
</label>
</p>
<button type="submit">Save</button>
</EditForm>
}
Note that the Routes that host the page should be in the new default static mode (i.e. no other RenderMode specified) and one should be using the new web app script
After discussing and reviewing comments, we iterated to the conclusion that the issue lays within the try{} catch{} blocks.
So, removing the NavigationManager.NavigateTo("/Products/" + product.ProductId); line from the try{} block made the difference.
Catching the exception (that is no harmful anyway) "eats" the navigation. Honestly I don't understand why it works like that. There are similar issues with pre-rendering and navigating within OnInitializedAsync, but nothing about .NET 8. I am embarked on a mission to unravel this behavior and will circle back with insights.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With