Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor route changes in same page

I'm current setup:

  • .NET core 3 (preview 6)
  • Blazor server side rendering

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.

like image 678
Gilian Avatar asked Jul 03 '19 11:07

Gilian


People also ask

How do you navigate from one page to another in Blazor?

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.

How does routing work in Blazor?

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.

How pass multiple parameters in URL Blazor?

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;} ... }

What is NavigationManager in Blazor?

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 .


1 Answers

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;  
    }
}

enter image description here

like image 141
dani herrera Avatar answered Sep 21 '22 11:09

dani herrera