I use URL parameters for page state in my app.
How can i change the URL without actually navigating?
Thanks!
(using blazor server side)
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 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.