Skip to content

Pass state using NavigationManager #829

@linkdotnet

Description

@linkdotnet

With the recent release of .net7-preview7 a new feature was introduced to pass state via the NavigationManager. Here the announcement on the official website.

If we have a component like that:

@page "/test"

@inject NavigationManager NavigationManager

<p>@(_entry ?? string.Empty)</p>

@code {
    private string? _entry;
    protected override void OnInitialized()
    {
        _entry = NavigationManager.HistoryEntryState;
    }

}

With a different component navigating to said component:

@inject NavigationManager NavigationManager

<button @onclick=@(() => NavigationManager.NavigateTo("/Test", new NavigationOptions {HistoryEntryState = "My Text"}))>Click</button>

A test could look like this (which currently fails, because bUnit does not set the HistoryEntryState in NavigateToCore):

Services.GetRequiredService<NavigationManager>()
    .NavigateTo("test/", new NavigationOptions() { HistoryEntryState = "Test" });

var cut = RenderComponent<ComponentWithEntryState>();

Assert.Equal("Test", cut.Find("p").TextContent);

What works out of the box is the follwing scenario:

@page "/"
@inject NavigationManager NavigationManager

<button @onclick=@(() => NavigationManager.NavigateTo("/Test", new NavigationOptions {HistoryEntryState = "Test"}))>Click</button>

@code {
    public string? NewState;
    
    protected override void OnInitialized()
    {
        NavigationManager.LocationChanged += (sender, args) => NewState = args.HistoryEntryState;
    }
}

With the following test:

var cut = RenderComponent<BlazorApp1.Pages.Index>();

cut.Find("button").Click();

Assert.Equal("Test", "Test");

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions