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.
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.navigationmanager.navigateto
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.
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