Send data between page and modal dialog in Blazored

972 views Asked by At

I have a page that lists some data in a table, in the last column I have created a

<td>
  <a class="nav-link" href="Edit/@item.id">
   <span class="oi oi-pencil" aria-hidden="true">Edit</span>
  </a>
</td>

That open the Edit page, and send the id with it. Recently, I found Balzored library which allow creating modal (pop up like) dialogs.

If I need to open a page, I would

<NavLink class="nav-link" @onclick="@(()=>modal.Show<Create>("Create"))">
   Add New
</NavLink>

But how can I pass the @item.id to the Edit page in Blazored.

The Edit page has @page "/edit/{Id}" as the first line.

1

There are 1 answers

3
Steve Greene On BEST ANSWER

First, I would not make the modal a page, make it a component. That is the beauty of Blazor. In that modal, you would add a parameter. It could be the id and you could go look it up again, or you could just pass the entire item you want to edit:

Your "Edit" modal should have something like this, and no @page directive - just make it a component:

[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
[Parameter] public int ItemId { get; set; }

In the main page that holds the table, create a method to handle the click and open the modal:

private async Task OnEditItemAsync(int ItemId)
{
    var parameters = new ModalParameters()
        .Add(nameof(Create.Id), ItemId);
    Modal.Show<Create>("Modal Title", parameters);
    // Add code to handle the modal result or refresh the table
    StateHasChanged();
}

In your table column, add a button that calls the method:

<td>
    <button onclick="@(async () => await OnEditItemAsync(item.Id))">Edit</button>
</td>

https://blazored.github.io/Modal/usage/passing-data