How to send data back from MudDialog

473 Views Asked by At

How can I send data from MudDialog (child) back to the component that instantiates the dialog (parent).

Sample class:

class Data
{
    string Name;
    int age;
}
1

There are 1 best solutions below

0
On BEST ANSWER

When you close the Dialog component using MudDialog.Close<T>() You can return a T object from the dialog.

CustomDialog.razor

<MudDialog>
    <DialogContent>
        <MudForm Model="PassedData">
            <MudTextField @bind-Value="PassedData.Name"></MudTextField>
            <MudNumericField @bind-Value="PassedData.Age" Variant="Variant.Text" Min="0" Max="500" />
        </MudForm>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">Cancel</MudButton>
        <MudButton Color="Color.Primary" OnClick="Submit">Submit</MudButton>
    </DialogActions>
</MudDialog>


@code {
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }
    [Parameter]
    public Data PassedData {get;set;}

    void Submit() 
    {
        MudDialog.Close<Data>(PassedData);  
    } 
    void Cancel() => MudDialog.Cancel();
}

Then in the page/component you show the dialog you can use the DialogService.GetReturnValueAsync<T>() method to get the returned object.

Page.razor

@code {
    Data _returnedData = null;
    private async Task OpenDialog()
    {    
        DialogOptions dialogOptions = new DialogOptions() { CloseOnEscapeKey = true };
        Data dataToPass = new(){Name="John", Age= 40};
        DialogParameters dialogParamters = new ()
        {
            ["PassedData"] = dataToPass
        };
        var dialog = await DialogService.ShowAsync<CustomDialog>("Custom Dialog", dialogParamters , dialogOptions);
        var result = await dialog.Result;
        if (!result.Canceled)
        {
            var returnedData = await dialog.GetReturnValueAsync<Data>();
            _returnedData = returnedData;
        }
    }
}

Have a look at this MudBlazor Snippet