Blazor: How to change the URL dynamically?

mb1*_*231 5 blazor

I have a page which takes a string bookingReference as its route parameter Booking/{bookingReference}.

This page is the parent component, with a child component inside where booking details are managed. The child component calls back to the parent when booking details are updated.

@page "/Booking/{bookingReference}"


<div class="header">
   <h1> @Booking.BookingReference </h1>
</div>

<div>
   <BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />
</div>


@code {

    [Parameter]
    public string BookingReference { get; set; }    

    private Booking Booking { get; set; }

    void UpdateBooking(Booking booking)
    {
        Booking = booking;
        StateHasChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

The BookingDetails component looks like this:

<EditForm Model="FormState" OnValidSubmit="@saveChanges">
   //inputs etc.
</EditForm>

@code {
    [Parameter]
    public Booking Booking { get; set; }

    [Parameter]
    public EventCallback<Booking> OnUpdateBooking { get; set; }

private async Task saveChanges()
{
        // update booking object
        Booking.BookingReference = FormState.BookingReference;

        try
        {
            Booking = await BookingService.UpdateBooking(Booking);
            await OnUpdateBooking.InvokeAsync(Booking);
            Toaster.Success("Booking updated successfully");
        }
        catch
        {
            Toaster.Error("Failed to update booking");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

The user can update the booking reference from the child component, and thus, change the header of the page - that works fine, all good.

However, I would also like to change the URL to the updated bookingReference - is there any way I can achieve this without forcing a refresh?

Isa*_*aac 7

好的,现在更改 url 中 BookingReference 值的唯一方法是使用新的 BookingReference 导航到当前 url。请注意,此操作不是重新加载或刷新页面组件。它更像是一个重新渲染的动作。OnInitialized 生命周期只执行一次,这表明组件不会被销毁然后重新创建。它们只是重新渲染。这是要走的路。

@code {

[Parameter]
public string BookingReference { get; set; }    

private Booking Booking { get; set; }

void UpdateBooking(Booking booking)
{
    Booking = booking;
    NavigationManager.NavigateTo($"/{Booking.BookingReference}");

}
}
Run Code Online (Sandbox Code Playgroud)