Terrence
Terrence

Reputation: 2804

Blazor StateObject lost after Navigation to next page

Blazor Server
Blazor Web App
InteractiveServer
.NET 8

builder.Services.AddScoped<NavParams>();

Working Normally:
I have a Blazor Web App with 20 pages.
I use NavParams as a statebag that is injected into each page.
I use NavigationManager.NavigateTo("myNextPage") in all page navigation.
This navigation is initiated by a mouse click on a link or button.
Everything works fine.

Not Working:
I have introduced Authentication.
The home page has
@attribute [Authorize]
Upon successful authentication I navigate to the next page but the NavParams.Hotel is null.
The difference is I an not initiating the navigation with a click event.

protected async override Task OnInitializedAsync()
{
    NavParams.Hotel = new Hotel();
    NavigationManager.NavigateTo(HotelRoutes.Details, forceLoad: false);
}

In the target page, HotelDetails, I load the NavParams object and gather the Hotel object

protected async override Task OnParametersSetAsync()
{
        Hotel = NavParams.Hotel;
        //Hotel is null 
}

Hotel is NULL

Upvotes: 1

Views: 56

Answers (1)

Terrence
Terrence

Reputation: 2804

I figured this out.

Turns out the landing page is a pass though page that merely authenticated the person and routed them to the appropriate page based on their credentials.

By triggering the navigation from the OnInitializedAsync method, a Signal-R circuit was not created before navigation.

Triggering the navigation from the OnAfterRenderAsync is late enough in the page lifecyle that a Signal-R circuit has been created and the next page gets the Navparams injected as expected.

Upvotes: 0

Related Questions