I'm current setup:
In a Blazor page I have something like the following:
@page "/page"
@page "/page/{Id}"
With:
[Parameter]
public string Id { get; set; }
Now, when navigating from, for example, /page/1
to /page/2
, I can use OnParametersSetAsync
to detect these changes. But the problem occurs when navigating from /page/1
to /page
. OnParametersSetAsync
can detect this change, however the Id
parameter will stay as 1
from the previous route.
I was wondering what i could do in this situation.
You can redirect to a page in Blazor using the Navigation Manager's NavigateTo method. In the following code snippet, it will redirect to the home page when this page gets loaded. Similarly, you can call NavigateTo() method from NavigationManager class anywhere to redirect to another page.
The Router component enables routing to Razor components in a Blazor app. The Router component is used in the App component of Blazor apps. When a Razor component ( . razor ) with an @page directive is compiled, the generated component class is provided a RouteAttribute specifying the component's route template.
The easiest way is to use Route parameters instead of QueryString: @page "/navigatetopage/{id:int}/{key}" @code { [Parameter] public int Id{get;set;} [Parameter] public string Key{get;set;} ... }
Access to browser navigation from Blazor is provided via the NavigationManager service. This can be injected into a Blazor component using @inject in a razor file, or the [Inject] attribute in a CS file. The NavigationManager service has two members that are of particular interest; NavigateTo and LocationChanged .
Blazor doesn't override empty parameters with null, do it by yourself:
@page "/Counter"
@page "/Counter/{Id}"
<h1>Current Id: @IdString;</h1>
<a href="/Counter"> go home </a> |
<a href="/Counter/1"> go home 1 </a> |
<a href="/Counter/2"> go home 2 </a>
@code
{
private string IdString;
[Parameter] public string Id { get; set; }
protected override async Task OnParametersSetAsync()
{
// copy par value somewhere
IdString = Id?.ToString() ?? "";
// rest parm (set to null) by yourself
Id=null;
}
}
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