Blazor equivalent of WPF ShowDialog()?

D. Hile picture D. Hile · Jul 31, 2019 · Viewed 7.7k times · Source

I'm attempting to migrate some code from WPF to Blazor. The WPF code relied on ShowDialog() to display a modal dialog and suspend execution until the modal was closed. Is there a (server-side) Blazor equivalent that allows C# flow of control to be based, for example, on whether the user clicked Acknowledge vs Cancel in a modal dialog?

Answer

Michael Washington picture Michael Washington · Jul 31, 2019

You can add a button

<button class="btn btn-primary"
  @onclick="AddNewForecast">
  Add New Forecast
</button>

That calls a method that sets a value to be true

bool ShowPopup = false;
void AddNewForecast()
{
    // Open the Popup
    ShowPopup = true;
}

And that value is wrapped around code that uses the bootstrap modal control (class="modal"):

        @if (ShowPopup)
        {
            <!-- This is the popup to create or edit a forecast -->
            <div class="modal" tabindex="-1" style="display:block" role="dialog">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h3 class="modal-title">Edit Forecast</h3>
                            <!-- Button to close the popup -->
                            <button type="button" class="close"
                                    @onclick="ClosePopup">
                                <span aria-hidden="true">X</span>
                            </button>
                        </div>
                        <!-- Edit form for the current forecast -->
                        <div class="modal-body">
                            <input class="form-control" type="text"
                                   placeholder="Celsius forecast"
                                   @bind="objWeatherForecast.TemperatureC" />
                            <input class="form-control" type="text"
                                   placeholder="Fahrenheit forecast"
                                   @bind="objWeatherForecast.TemperatureF" />
                            <input class="form-control" type="text"
                                   placeholder="Summary"
                                   @bind="objWeatherForecast.Summary" />
                            <br />
                            <!-- Button to save the forecast -->
                            <button class="btn btn-primary"
                                    @onclick="SaveForecast">
                                Save
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        }

You will have a popup that is "modal"