Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor Navigation: Update URL without changing reloading page

I use URL parameters for page state in my app.

How can i change the URL without actually navigating?

Thanks!

(using blazor server side)

like image 819
Tom Crosman Avatar asked Mar 02 '20 18:03

Tom Crosman


2 Answers

If you just want to add/remove/change query parameters in the URL, use the NavigationManager.NavigateTo method. It will not reload the page if it is not necessary (or not called with forceReload flag).

For example, the current URL is "https://example.com/page", then call NavigationManager.NavigateTo("https://example.com/page?id=1") will not reload the page but only modify URL. Click "Back" in browser will change the URL to "https://example.com/page", this change can be handled with NavigationManager.LocationChanged event.

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.navigationmanager.navigateto

like image 30
Daniil Palii Avatar answered Sep 16 '22 12:09

Daniil Palii


You can do this with JS Interop and call history.pushState(null, '', url)

Here is a simple example

.razor

@page "/"
@inject IJSRuntime jsRuntime

<input
    @bind="url"
/>

<button @onclick="ChangeUrl">
    Change Url
</button>

<p>@url</p>

@code {
    [Parameter]
    public string Url { get; set; }

    void ChangeUrl(){
        // You can also change it to any url you want
        jsRuntime.InvokeVoidAsync("ChangeUrl", Url);
    }
}

.js

window.ChangeUrl = function(url){
    history.pushState(null, '', url);   
}

Please notice that this only works for visual purpose, it will only change for the browser while in the server side, you probably won't see the change.

like image 104
Vencovsky Avatar answered Sep 16 '22 12:09

Vencovsky