Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor: How to change the URL dynamically?

Tags:

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

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

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?

like image 930
mb1231 Avatar asked Feb 18 '20 10:02

mb1231


1 Answers

Ok, right now the only way to change the value of the BookingReference in the url is to navigate to the current url with the new BookingReference. Note that this action is not reloading or refreshing the page component. It is rather a re-rendering action. The OnInitialized life cycle is executed only once, which indicates that the components are not destroyed and then re-created. They are only re-rendered. This is the way to go.

@code {

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

private Booking Booking { get; set; }

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

}
}
like image 151
enet Avatar answered Sep 28 '22 10:09

enet