I use URL parameters for page state in my app.
How can i change the URL without actually navigating?
Thanks!
(using blazor server side)
I use URL parameters for page state in my app.
How can i change the URL without actually navigating?
Thanks!
(using blazor server side)
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.
NavigateTo is that it would actually navigate, and initialize the page/component matching that route again, which, as I understand it, the OP are looking to avoid.navigationManager.NavigateTo("/counter/50");NavigationManager#GetUriWithQueryParameters() to create a URL based on the current URL with the required parameters set accoring to the values within the dictionary.navigateTo(..., forceLoad: false)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.
jsRuntime.InvokeVoidAsync("ChangeUrl", Url); on this case,as the function does not return anything?NavigationManager.NavigateTo method. It will not reload the page if it is not necessary (or not called with forceReload flag). Then history will be handled properly and NavigationManager.LocationChanged event will be fired.await JSRuntime.InvokeVoidAsync("history.pushState", null, "", Url);. Since history is part of window already, you don't need to write a JS function to expose it.