# Blazor Dialog, Window and Message Box

URL: https://flexcoreui.com/demo/dialog  
Section: Components  
Controls: DialogControl, MessageBoxControl, IDialogService  
Keywords: dialog, modal, window, message box, popup, confirm dialog

Blazor dialogs and message boxes: movable, resizable windows, modal or not, plus awaitable confirm, alert and prompt from IDialogService.

## Documentation

### Dialog

| Name | Type | Default | Description |
|---|---|---|---|
| Visible | bool | false | Shown or not. Two-way with @bind-Visible; closing sets it false. |
| Header | string? | null | Title-bar text; also the accessible name. |
| HeaderContent | RenderFragment? | null | Title-bar markup in place of Header's plain text, such as a ticket subject with a smaller caption. Dragging, the window menu and the close button work as with Header, and it names the dialog the same way. |
| ChildContent | RenderFragment? |  | Body. |
| FooterContent | RenderFragment? | null | Footer, right-aligned flex row. Rendered only when set. |
| Width / Height | string? | null | CSS sizes. Two-way: a resize reports the new values through WidthChanged / HeightChanged. |
| Position | DialogPosition? | null | Offset from center after a drag. Two-way with @bind-Position. |
| IsModal | bool | true | true dims and blocks the page; false leaves it live. |
| ShowCloseIcon | bool | true | The ✕ in the title bar. |
| CloseOnEscape | bool | true | Escape requests close. |
| OnEscape | EventCallback |  | When set, Escape runs this instead of closing. For dialogs whose close commits. |
| OnEnter | EventCallback |  | Default button. A plain Enter anywhere in the dialog runs it after the focused control has handled the key; buttons, links, editors, grids and open dropdowns keep Enter. |
| CloseOnCtrlEnter | bool | false | Ctrl+Enter requests close. |
| HostKeyboardShortcuts | IReadOnlyCollection<string>? | null | Keys your page handles for the whole window, written like "Ctrl+S" or "Meta+S", modifiers in the order Ctrl, Alt, Shift, Meta. The dialog stops the browser's own action for them, such as saving the page, wherever focus is, and lets the key reach your handler. A nested dialog keeps its own keys. |
| CloseOnOverlayClick | bool | false | A click on the dimmed backdrop requests close. |
| OnClose / Closed | EventCallback |  | Both run on every close request (✕, Escape, Alt+F4, system menu), in that order, then Visible goes false. |
| Draggable | bool | true | Title bar drags the window. |
| Resizable | bool | true | Eight resize handles. |
| MinResizeWidth / MinResizeHeight | double | 320 / 160 | Resize floor in pixels. |
| MaxResizeWidth / MaxResizeHeight | double | 0 | Resize ceiling in pixels; 0 means none. |
| ShowSystemMenu | bool | true | Right-click on the title bar opens the Move / Close menu. |
| ShowWindowIcon | bool | false | Icon at the left of the title bar that opens the same menu. |
| AutoFocus | bool | true | Focus the first focusable control on open. |
| AriaLabel / AriaDescribedBy | string? | null | Accessible name when there is no header; id of a description. |
| CssClass | string? | null | Extra classes on the window; fx-dialog-classic switches the frame. |

### Service

| Name | Type | Description |
|---|---|---|
| ConfirmAsync(message, title) | Task<bool> | Yes / No box; true for Yes. |
| ConfirmCancelAsync(message, title) | Task<MessageBoxResult> | Yes / No / Cancel box. |
| AlertAsync(message, title) | Task | OK box. |
| PromptAsync(message, title, defaultValue) | Task<string?> | Single-line input; null when canceled. |

### Message box

| Name | Type | Default | Description |
|---|---|---|---|
| Visible | bool | false | Two-way; ShowAsync sets it for you. |
| Title / Message | string | "Message" / null | Title bar and body text. |
| Buttons | MessageBoxButtons | Ok | Which buttons to show. |
| IconCss | string? | null | Keyword warning, info, error, question or none; any other value is used as a CSS class. The VB6 look shows the question icon by default on boxes with more than OK. |
| Look | MessageBoxLook | VB6 | VB6 classic frame or DotNet. |
| RequiredConfirmationText | string? | null | Adds a checkbox with this label; the primary button stays disabled until it is checked. |
| Draggable | bool | true | Title bar drags the box. |
| CloseOnOverlayClick | bool | false | Backdrop click closes. |
| OnResult | EventCallback<MessageBoxResult> |  | Fires with the chosen button. |
| CssClass | string? | null | Extra classes on the box. |

### Input

| Name | Type | Default | Description |
|---|---|---|---|
| Visible | bool | false | Two-way; ShowAsync sets it for you. |
| Title / Prompt | string | "Input" / null | Title bar and the label above the box. |
| InputValue | string | "" | Current text. |
| Placeholder / InputType | string? / string | null / "text" | Passed to the text box. |
| MaxLength | int | 256 | Passed to the text box. |
| OnResult | EventCallback<string?> |  | Fires with the text, or null on cancel. |
| CssClass | string? | null | Extra classes on the dialog. |

### Methods

| Name | Type | Description |
|---|---|---|
| MessageBoxControl.ShowAsync(message, title, buttons, icon, look, requiredConfirmationText) | Task<MessageBoxResult> | Shows the box and completes with the chosen button. All but message optional; icon takes the same keywords as IconCss. |
| InputDialogControl.ShowAsync(prompt, title, defaultValue) | Task<string?> | Shows the prompt; null when canceled. |
| MultiLineEditControl.ShowAsync(initial, title, maxLength, prompt) | Task<string?> | Multi-line text prompt; null when canceled. |
| DefaultButtonScope.ConsumeEnter() | void | Cascaded by a dialog with OnEnter. A control calls it to keep one Enter for itself. |
| DefaultButtonScope.Defer(decision) | void | The default button waits for this task before deciding. |

### Css

| Name | Description |
|---|---|
| fx-dialog-overlay · .fx-dialog-overlay-nonmodal | Fixed full-screen layer, 35% black and centered; non-modal makes it transparent and lets clicks through. |
| fx-dialog · .fx-dialog-classic | The window: white, rounded, shadow, 320px minimum, 90vw / 90vh maximum. Classic: gray, square 28px title bar, MS Sans Serif. |
| fx-dialog-header · fx-dialog-title · fx-dialog-close · fx-dialog-window-icon | Title bar parts. The ✕ turns red on hover. |
| fx-dialog-body · fx-dialog-footer | Body with 16px padding; footer with a top border, right-aligned. |
| fx-dialog-btn | Footer button styling that any button can take. |
| fx-dialog-resize-n … fx-dialog-resize-nw | The eight invisible resize handles. |
| fx-dialog-system-menu | The Win32-style menu. |
| fx-msgbox · .fx-msgbox-vb6 · .fx-msgbox-dotnet | Message box frame in each look. |

### Vars

| Name | Type | Description |
|---|---|---|
| --fx-dialog-bg | #fff | Window, body and footer background. |
| --fx-border-radius | 8px | Corner radius. |
| --fx-dialog-border / --fx-dialog-border-color | none | Window border. |
| --fx-dialog-shadow | 0 6px 24px rgba(0,0,0,.2) | Window shadow. |
| --fx-dialog-header-bg / --fx-dialog-header-color | transparent / inherit | Title bar. |
| --fx-border-color | #e0e0e0 | Header and footer dividers. |
| --fx-text-color | inherit | Body text. |
| --fx-zoom | 1 | Scales the classic frame, close icon and system menu. |

## Examples

### Modal

```razor
@using Fx.ControlKit

<ToggleButtonControl @bind-Selected="_classic">Classic look</ToggleButtonControl>

<div class="tk-card" role="status">
    <div>
        <strong>TKT-1042 · Albus Door · Router keeps restarting</strong>
        <div class="result">Follow up @_followUp.ToString("ddd MMM d") · @_priority priority · Note: @(string.IsNullOrWhiteSpace(_note) ? "none" : _note)</div>
    </div>
    <ButtonControl CssClass="btn-primary" OnClick="OpenEdit">Edit ticket</ButtonControl>
</div>
@* Classic: the frame class, the window icon, classic buttons; .dlg-host lets page CSS gray the footer. *@
<div class="dlg-host">
    <DialogControl @bind-Visible="_editOpen" Header="Edit ticket TKT-1042" Width="440px" OnEnter="Save"
                   CssClass="@(_classic ? "fx-dialog-classic" : null)" ShowWindowIcon="@_classic">
        <ChildContent>
            <p class="dlg-text">Change the ticket for <strong>Albus Door</strong>, then press Enter or Save.</p>
            <div style="display:grid; grid-template-columns:auto 1fr; gap:6px 10px; align-items:center;">
                <span>Follow up</span><DatePickerControl @bind-Value="_editFollowUp" MinDate="DateTime.Today" />
                <span>Priority</span><DropDownListControl TItem="string" TValue="string" DataSource="@_priorities" @bind-Value="_editPriority" Width="180px" />
                <span>Note</span><TextBoxControl @bind-Value="_editNote" TypingBehavior="TextBoxTypingBehavior.ClientBuffered" Placeholder="Optional note" />
            </div>
        </ChildContent>
        <FooterContent>
            <ButtonControl CssClass="@(_classic ? "fx-button-classic" : "btn-primary")" OnClick="Save">Save</ButtonControl>
            <ButtonControl CssClass="@(_classic ? "fx-button-classic" : "btn-secondary")" OnClick="@(() => _editOpen = false)">Cancel</ButtonControl>
        </FooterContent>
    </DialogControl>
</div>
```

```csharp
// Modal: the dialog edits copies, and Save writes them to the ticket
private bool _editOpen, _classic;
private DateTime _followUp = DateTime.Today.AddDays(2);
private string _priority = "High";
private string _note = "";
private DateTime? _editFollowUp;
private string _editPriority = "", _editNote = "";
private readonly List<string> _priorities = new() { "Low", "Normal", "High", "Urgent" };
private void OpenEdit()
{
    (_editFollowUp, _editPriority, _editNote) = (_followUp, _priority, _note);
    _editOpen = true;
}
private void Save()
{
    (_followUp, _priority, _note) = (_editFollowUp ?? _followUp, _editPriority, _editNote);
    _editOpen = false;
}
```

### Window

```razor
@using Fx.ControlKit

<div class="demo-row">
    @foreach (var ticket in Tickets)
    {
        <ButtonControl CssClass="@(ticket == _ticket ? "btn-sm btn-primary" : "btn-sm")" OnClick="() => _ticket = ticket">@ticket.Code</ButtonControl>
    }
    <ButtonControl OnClick="@(() => _winOpen = true)" Disabled="_winOpen">Open ticket details</ButtonControl>
    <span class="result" role="status">@_winWidth × @_winHeight, @(_winPos is null ? "centered" : $"moved {_winPos.X:0}, {_winPos.Y:0}")</span>
</div>
<DialogControl @bind-Visible="_winOpen" Header="@($"Ticket details: {_ticket.Code}")" IsModal="false" ShowWindowIcon="true"
               @bind-Width="_winWidth" @bind-Height="_winHeight" @bind-Position="_winPos"
               MinResizeWidth="360" MinResizeHeight="200">
    <p class="dlg-text"><strong>@_ticket.Subject</strong>, reported by @_ticket.Customer</p>
    <p class="dlg-text">@_ticket.Details</p>
    <p class="dlg-text result">Pick another ticket on the page: this window stays open and follows it.</p>
</DialogControl>
```

```csharp
// Window
private sealed record Ticket(string Code, string Subject, string Customer, string Details);
private static readonly Ticket[] Tickets =
{
    new("TKT-1042", "Router keeps restarting", "Albus Door", "Hardware queue, by phone. Restarts every evening since Monday."),
    new("TKT-1043", "Charged twice in October", "Hermione Ranger", "Billing queue, by email. Two October charges on the same card."),
    new("TKT-1044", "Cannot reset password", "Ron Measly", "Accounts queue, by chat. The reset email never arrives."),
    new("TKT-1045", "Slow connection in the evenings", "Luna Goodlove", "Connection queue, by phone. Video calls freeze after 7 PM."),
};
private Ticket _ticket = Tickets[0];
private bool _winOpen;
private string? _winWidth = "480px", _winHeight = "240px";
private DialogPosition? _winPos;
```

### Service

```razor
@using Fx.ControlKit
@using Fx.ControlKit.Dialogs

<div class="tk-card" role="status">
    <div>
        <strong>TKT-1043 · Hermione Ranger · @_subject</strong>
        <div class="result">Status: @_status · Notes: @_notes.Length characters</div>
    </div>
</div>
<div class="demo-row mt">
    <ButtonControl OnClick="Rename" Disabled="@(_status == "Solved")">Rename ticket</ButtonControl>
    <ButtonControl OnClick="Notes" Disabled="@(_status == "Solved")">Notes, multi-line</ButtonControl>
    <ButtonControl OnClick="SendReply" Disabled="@(_status != "Open")">Send reply</ButtonControl>
    <ButtonControl CssClass="btn-danger" OnClick="RefundCharge" Disabled="@(_status == "Solved")">Refund charge</ButtonControl>
    <ButtonControl OnClick="Restore" Disabled="@(_status == "Open" && _subject == "Charged twice in October" && _notes.Length == 0)">Start over</ButtonControl>
</div>
<MessageBoxControl @ref="_box" />
<MultiLineEditControl @ref="_editor" />
```

```csharp
// Service and message box. Set-up, once per app: Program.cs registers
//   builder.Services.AddScoped<Fx.ControlKit.Dialogs.DialogService>();
//   builder.Services.AddScoped<Fx.ControlKit.Dialogs.IDialogService>(sp => sp.GetRequiredService<Fx.ControlKit.Dialogs.DialogService>());
// and MainLayout.razor hosts <DialogHostControl />. This page has @inject IDialogService Dialogs at the top.
private MessageBoxControl? _box;
private MultiLineEditControl? _editor;
private string _subject = "Charged twice in October", _status = "Open", _notes = "";
private async Task Rename()
{
    var subject = await Dialogs.PromptAsync("Subject:", "Rename ticket", _subject);
    if (!string.IsNullOrWhiteSpace(subject)) _subject = subject;
}
private async Task Notes()
{
    var text = await _editor!.ShowAsync(_notes, "Ticket notes", 500, "Internal notes for the ticket; 500 characters at most.");
    if (text is not null) _notes = text;
}
private async Task SendReply()
{
    if (!await Dialogs.ConfirmAsync($"{_subject}: send the reply to Hermione Ranger?", "Send reply")) return;
    _status = "Waiting on customer";
    StateHasChanged();   // show the new status behind the alert
    await Dialogs.AlertAsync("The reply is on its way. The customer has 7 days to answer.", "Reply sent");
}
private async Task RefundCharge()
{
    var answer = await _box!.ShowAsync($"{_subject}: refund the duplicate charge and solve the ticket?", "Refund charge", MessageBoxButtons.OkCancel, "warning", null, "I understand this cannot be undone");
    if (answer == MessageBoxResult.Ok) _status = "Solved";
}
private void Restore() => (_subject, _status, _notes) = ("Charged twice in October", "Open", "");
```

