Learn to Create a Simple Dialog Box in Blazor

Dialog Box

Creating a Dialog Box using Blazor is simple. Dialog Boxes used to be a space where you could notify or receive specific input from the user to finish a process or get confirmation.

The sample I'm using on the article has a button to open the dialog and a button inside to close it.

We will add this code directly to the razor page. The dialog can be decorated in CSS. The content for the dialog box should match the software requirements you are building.

The tag for the dialog box is "dialog", and you can add the events, ID, and other specific needs.

<style>
    dialog {
        border: 1px solid black;
        padding: 1rem;
        width: 440px;
        height: 200px;
    }
</style>

<div>
    <p>Output: @message</p>

    <button onclick="document.getElementById('my-dialog').showModal()">
        Show modal dialog
    </button>

    <dialog id="my-dialog" @onclose="OnClose" @oncancel="OnCancel">
        <p>Hi there!</p>

        <form method="dialog">
            <button>Close</button>
        </form>
    </dialog>
</div>

@code {
    private string? message;

    private void OnClose(EventArgs e) => message += "onclose, ";

    private void OnCancel(EventArgs e) => message += "oncancel, ";
}

This is the result of the code above.

A button to show the modal dialog;

The Dialog Box with Hi there!

And the "Close" button.

Close button

Tip. Mastering a language or technology starts better when we play as kids with the "toys", so I recommend that any students spend time creating and building pieces of software to understand the concepts and the limits of the tools deeply.


Similar Articles