### Install Blazored.Modal NuGet Package
Source: https://github.com/blazored/modal/blob/main/docs/docs/getting-started.md
Install the Blazored.Modal package using PowerShell Package Manager Console or .NET CLI. This is the first step to add modal functionality to a Blazor application.
```powershell
Install-Package Blazored.Modal
```
```bash
dotnet add package Blazored.Modal
```
--------------------------------
### Register Blazored Modal Service in Program.cs
Source: https://github.com/blazored/modal/blob/main/docs/docs/getting-started.md
Add the Blazored.Modal namespace import and register the modal service in the dependency injection container using AddBlazoredModal(). This setup is required in Program.cs with top-level statements.
```csharp
using Blazored.Modal;
builder.Services.AddBlazoredModal();
```
--------------------------------
### Display Modal Using IModalService
Source: https://github.com/blazored/modal/blob/main/docs/docs/getting-started.md
Define a cascading parameter for IModalService in a component and use the Show method to display a modal. Pass the modal title and the component type to display. This example shows a button click that displays a Movies component in a modal.
```razor
@page "/"
Hello, world!
Welcome to Blazored Modal.
@code {
[CascadingParameter] public IModalService Modal { get; set; }
}
```
--------------------------------
### Add Blazored Modal Imports to _Imports.razor
Source: https://github.com/blazored/modal/blob/main/docs/docs/getting-started.md
Add using statements for Blazored.Modal and Blazored.Modal.Services to the root _Imports.razor file. This makes these namespaces available to all components in the project without requiring individual using statements.
```razor
@using Blazored.Modal
@using Blazored.Modal.Services
```
--------------------------------
### Add CascadingBlazoredModal Component to App.razor
Source: https://github.com/blazored/modal/blob/main/docs/docs/getting-started.md
Wrap the Router component with CascadingBlazoredModal in the root App.razor component. This cascades the IModalService instance to all descendant components, enabling modal functionality throughout the application.
```html
...
```
--------------------------------
### Add CSS Reference for Blazored Modal
Source: https://github.com/blazored/modal/blob/main/docs/docs/getting-started.md
Include the CSS bundle reference in the HTML head section if CSS isolation is not already enabled in the application. This line should be added to index.html or the appropriate layout file, replacing {YOUR APP ASSEMBLY NAME} with the actual assembly name.
```html
```
--------------------------------
### Setup CascadingBlazoredModal in Router (Razor)
Source: https://context7.com/blazored/modal/llms.txt
Wraps the application's router with CascadingBlazoredModal to enable modal dialogs. This setup is crucial for the modal service to function correctly within the Blazor component hierarchy.
```razor
```
--------------------------------
### Blazored ModalParameters API
Source: https://context7.com/blazored/modal/llms.txt
Provides a fluent API for passing parameters to modal components. Use the Add method to chain parameter additions and Get or TryGet to retrieve them. Parameters can be of any object type.
```csharp
public class ModalParameters : IEnumerable>
{
// Add a parameter (chainable)
public ModalParameters Add(string parameterName, object? value);
// Get a parameter (throws if not found or wrong type)
public T Get(string parameterName);
// Try get a parameter (returns null if not found)
public T? TryGet(string parameterName) where T : class;
}
```
```csharp
// Usage examples
var parameters = new ModalParameters()
.Add("UserId", 123)
.Add("UserName", "John Doe")
.Add("IsActive", true)
.Add("ComplexObject", new MyData());
// In modal component
[Parameter] public int UserId { get; set; }
[Parameter] public string UserName { get; set; } = "";
[Parameter] public bool IsActive { get; set; }
[Parameter] public MyData? ComplexObject { get; set; }
```
--------------------------------
### Handle Complex Modal Results
Source: https://context7.com/blazored/modal/llms.txt
Example demonstrating how to pass complex data to a modal and receive complex results back, including checking confirmation status.
```APIDOC
## Handle Complex Modal Results
Return complex objects and check result status.
### Description
This example shows how to:
1. Define a complex data structure (`UserData`) to pass to and receive from a modal.
2. Show a modal (`UserForm`) with initial parameters.
3. Wait for the modal result and check if it was confirmed.
4. Process the complex data (`UserData`) returned from the modal.
### Request Example (Showing the Modal)
```razor
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
public class UserData
{
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
async Task ShowUserForm()
{
var parameters = new ModalParameters
{
{ "InitialName", "John Doe" }
};
var modalRef = Modal.Show("Edit User", parameters);
var result = await modalRef.Result;
if (result.Confirmed) // Same as !result.Cancelled
{
if (result.Data is UserData userData)
{
Console.WriteLine($"Name: {userData.Name}, Email: {userData.Email}");
}
}
}
}
```
### Request Example (UserForm Component)
```razor
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
[Parameter] public string InitialName { get; set; } = "";
private string Name { get; set; } = "";
private string Email { get; set; } = "";
protected override void OnInitialized()
{
Name = InitialName;
}
async Task Save()
{
var userData = new UserData
{
Name = Name,
Email = Email
};
await BlazoredModal.CloseAsync(ModalResult.Ok(userData));
}
async Task Cancel()
{
await BlazoredModal.CancelAsync();
}
}
```
### Response
- **result.Confirmed** (`bool`): Indicates if the modal was confirmed (true) or cancelled (false).
- **result.Data** (`object`): The data returned from the modal. In this example, it's expected to be of type `UserData` if confirmed.
```
--------------------------------
### Blazored IModalReference API for Parent Control
Source: https://context7.com/blazored/modal/llms.txt
Reference returned when showing a modal, allowing parent components to control it. Await the Result property to get the modal's outcome or use Close() to dismiss it programmatically.
```csharp
public interface IModalReference
{
// Await this to get the modal result
Task Result { get; }
// Close the modal from parent component
void Close();
void Close(ModalResult result);
}
```
```csharp
// Usage example
var modalRef = Modal.Show();
// Wait for user to close modal
var result = await modalRef.Result;
// Or close it programmatically
modalRef.Close();
modalRef.Close(ModalResult.Ok());
```
--------------------------------
### Pass Data to Modal Component (Razor)
Source: https://context7.com/blazored/modal/llms.txt
Illustrates how to pass data to a modal component using `ModalParameters`. This example shows sending a string message to a modal for display or further processing. The modal component must define a corresponding parameter.
```razor
@page "/passingdata"
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
string _message = "";
void ShowModal()
{
var parameters = new ModalParameters
{
{ nameof(DisplayMessage.Message), _message }
};
Modal.Show("Passing Data", parameters);
_message = "";
}
}
```
--------------------------------
### Configure Blazored Modal Predefined Position for Single Modal (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/position.md
Configure a single Blazored Modal instance to use a predefined position by setting the `Position` property within `ModalOptions`. This example shows how to set the position to Top Left when showing a modal.
```csharp
var options = new ModalOptions()
{
Position = ModalPosition.TopLeft
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Configure Blazored Modal Predefined Position Globally (Razor)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/position.md
Configure Blazored Modal to use a predefined position for all modals by setting the `Position` attribute in `CascadingBlazoredModal` component. This example sets the position to Top Left.
```razor
```
--------------------------------
### Close Modal Programmatically with C# Example
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/closing-programmatically.md
Demonstrates how to close a Blazored Modal programmatically using C#. This is useful for scenarios like showing a loading spinner while a task completes, after which the modal is automatically closed. It utilizes the `IModalService` and `IModalReference` interfaces.
```csharp
[CascadingParameter] IModalService Modal { get; set; } = default!;
private async Task ShowSpinner()
{
var spinnerModal = Modal.Show();
await MyLongRunningTask();
spinnerModal.Close();
}
```
--------------------------------
### Dynamically Update Blazored Modal Title
Source: https://context7.com/blazored/modal/llms.txt
Shows how to dynamically change the title of a Blazored Modal after it has been displayed. This is achieved by injecting the BlazoredModalInstance into the modal component and calling the SetTitle method. The example includes a progress indicator that updates the modal title.
```razor
Processing... @_progress%
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
private int _progress = 0;
protected override void OnInitialized()
{
BlazoredModal.SetTitle("Initial Title");
}
void UpdateProgress()
{
_progress += 10;
BlazoredModal.SetTitle($"Processing: {_progress}%");
}
}
```
--------------------------------
### Blazor.start Configuration for GitHub Pages Resource Loading
Source: https://github.com/blazored/modal/blob/main/samples/InteractiveWebAssembly/wwwroot/index.html
This configuration snippet initializes Blazor WebAssembly, providing a custom `loadBootResource` function. This function attempts to load Brotli-compressed resources (`.br`) for faster downloads, which is particularly useful on GitHub Pages where native compression support might be limited. It includes a fallback to default URI loading if Brotli is not available or if the application is running on localhost. It also handles different content types for .NET runtime and WebAssembly files.
```javascript
Blazor.start({ loadBootResource: function (type, name, defaultUri, integrity) { if (type !== 'dotnetjs' && location.hostname !== 'localhost') { return (async function () { const response = await fetch(defaultUri + '.br', { cache: 'no-cache' }); if (!response.ok) { throw new Error(response.statusText); } const originalResponseBuffer = await response.arrayBuffer(); const originalResponseArray = new Int8Array(originalResponseBuffer); const decompressedResponseArray = BrotliDecode(originalResponseArray); const contentType = type === 'dotnetwasm' ? 'application/wasm' : 'application/octet-stream'; return new Response(decompressedResponseArray, { headers: { 'content-type': contentType } }); })(); } } });
```
--------------------------------
### IModalService API Reference
Source: https://context7.com/blazored/modal/llms.txt
Reference for the IModalService, detailing various overloads for showing modals with different configurations.
```APIDOC
## IModalService API Reference
Complete API for showing modals with all overload variations.
### Method
`IModalReference Show(...)` where `TComponent` is an `IComponent`
### Overloads
1. **Basic Modal Display**
```csharp
IModalReference Show() where TComponent : IComponent;
IModalReference Show(string title) where TComponent : IComponent;
```
2. **With Options**
```csharp
IModalReference Show(ModalOptions options) where TComponent : IComponent;
IModalReference Show(string title, ModalOptions options) where TComponent : IComponent;
```
3. **With Parameters**
```csharp
IModalReference Show(ModalParameters parameters) where TComponent : IComponent;
IModalReference Show(string title, ModalParameters parameters) where TComponent : IComponent;
```
4. **With Both Parameters and Options**
```csharp
IModalReference Show(ModalParameters parameters, ModalOptions options) where TComponent : IComponent;
IModalReference Show(string title, ModalParameters parameters, ModalOptions options) where TComponent : IComponent;
```
5. **Type-Based Variants** (using `Type` instead of generic)
```csharp
IModalReference Show(Type component);
IModalReference Show(Type component, string title);
IModalReference Show(Type component, string title, ModalOptions options);
IModalReference Show(Type component, string title, ModalParameters parameters);
IModalReference Show(Type component, string title, ModalParameters parameters, ModalOptions options);
```
### Response
- **IModalReference**: An object that provides a reference to the modal instance, allowing for interaction like closing or getting results.
```
--------------------------------
### Show Basic Modal Dialog (Razor)
Source: https://context7.com/blazored/modal/llms.txt
Demonstrates how to display a simple modal dialog with a title using the Blazored Modal service. It requires the `IModalService` to be injected via cascading parameters.
```razor
@page "/"
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
void ShowModal()
=> Modal.Show("Welcome to Blazored Modal");
}
```
--------------------------------
### ModalOptions Configuration Reference
Source: https://context7.com/blazored/modal/llms.txt
Reference for ModalOptions, detailing all available configuration properties for customizing modal display and behavior.
```APIDOC
## ModalOptions Configuration Reference
All available configuration options for modal display.
### Class
`ModalOptions`
### Properties
#### Size Options
- **Size** (`ModalSize?`): Specifies the size of the modal (Small, Medium, Large, ExtraLarge, Custom, Automatic).
- **SizeCustomClass** (`string?`): A CSS class to apply when `Size` is set to `Custom`.
#### Position Options
- **Position** (`ModalPosition?`): Specifies the position of the modal (TopCenter, TopLeft, TopRight, Middle, BottomLeft, BottomRight, Custom).
- **PositionCustomClass** (`string?`): A CSS class to apply when `Position` is set to `Custom`.
#### Animation Options
- **AnimationType** (`ModalAnimationType?`): The animation type for the modal (FadeInOut, PopInOut, PopIn, None).
#### Styling Options
- **Class** (`string?`): A custom CSS class to apply to the modal itself.
- **OverlayCustomClass** (`string?`): A custom CSS class to apply to the modal's overlay/backdrop.
#### Behavior Options
- **DisableBackgroundCancel** (`bool?`): If true, prevents the modal from closing when the backdrop is clicked.
- **HideHeader** (`bool?`): If true, hides the entire modal header.
- **HideCloseButton** (`bool?`): If true, hides the close button (X) in the header.
- **UseCustomLayout** (`bool?`): If true, allows for a completely custom HTML structure for the modal.
- **ActivateFocusTrap** (`bool?`): If true, enables keyboard focus trapping for improved accessibility within the modal.
```
--------------------------------
### Blazor IModalService API Reference for Showing Modals
Source: https://context7.com/blazored/modal/llms.txt
Provides the interface definition for IModalService, detailing all available overloads for displaying modals. This includes options for specifying the component type, title, parameters, and modal options. It covers both generic and type-based variants.
```csharp
public interface IModalService
{
// Basic modal display
IModalReference Show() where TComponent : IComponent;
IModalReference Show(string title) where TComponent : IComponent;
// With options
IModalReference Show(ModalOptions options) where TComponent : IComponent;
IModalReference Show(string title, ModalOptions options) where TComponent : IComponent;
// With parameters
IModalReference Show(ModalParameters parameters) where TComponent : IComponent;
IModalReference Show(string title, ModalParameters parameters) where TComponent : IComponent;
// With both parameters and options
IModalReference Show(ModalParameters parameters, ModalOptions options) where TComponent : IComponent;
IModalReference Show(string title, ModalParameters parameters, ModalOptions options) where TComponent : IComponent;
// Type-based variants (same patterns using Type instead of generic)
IModalReference Show(Type component);
IModalReference Show(Type component, string title);
IModalReference Show(Type component, string title, ModalOptions options);
IModalReference Show(Type component, string title, ModalParameters parameters);
IModalReference Show(Type component, string title, ModalParameters parameters, ModalOptions options);
}
```
--------------------------------
### URL Rewriting for GitHub Pages SPA
Source: https://github.com/blazored/modal/blob/main/samples/InteractiveWebAssembly/wwwroot/404.html
This JavaScript code rewrites the current URL to support Single Page Applications on GitHub Pages. It takes the current path and query string, converts them into 'p' and 'q' query parameters respectively, and redirects the browser. This is necessary because GitHub Pages serves a static index.html for all routes, and this script helps the client-side router to determine the correct view. It requires no external dependencies.
```javascript
var segmentCount = 1;
var l = window.location;
l.replace( l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') + l.pathname.split('/').slice(0, 1 + segmentCount).join('/') + '/?p=/' + l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') + (l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') + l.hash );
```
--------------------------------
### Show First Modal from Homepage (Razor)
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/multiple-modals.md
This snippet shows how to trigger the display of the first modal ('ModalOne') from a button click in the 'Homepage' component. It utilizes the Blazored ModalService to instantiate and display the modal.
```razor
@code {
[CascadingParameter] IModalService ModalService { get; set; } = default!;
private void ShowModal() => ModalService.Show("First Modal");
}
```
--------------------------------
### Register Blazored Modal Service (C#)
Source: https://context7.com/blazored/modal/llms.txt
Registers the Blazored Modal service within the application's service collection. This is a prerequisite for using any modal functionality. It uses the standard .NET generic host builder pattern.
```csharp
using Blazored.Modal;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// Register Blazored Modal service
builder.Services.AddBlazoredModal();
var app = builder.Build();
app.Run();
```
--------------------------------
### Handle Query String Redirects for Blazor on GitHub Pages
Source: https://github.com/blazored/modal/blob/main/samples/InteractiveWebAssembly/wwwroot/index.html
This JavaScript snippet intercepts query string parameters, specifically 'p' for path and 'q' for query, and reconstructs the correct URL. It then uses `window.history.replaceState` to update the browser's history without causing a page reload, ensuring the Blazor application receives the correct routing information upon initialization. This is crucial for Single Page Applications hosted on platforms like GitHub Pages.
```javascript
(function (l) { if (l.search) { var q = {}; l.search.slice(1).split('&').forEach(function (v) { var a = v.split('='); q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&'); }); if (q.p !== undefined) { window.history.replaceState(null, null, l.pathname.slice(0, -1) + (q.p || '') + (q.q ? ('?' + q.q) : '') + l.hash ); } } }(window.location))
```
--------------------------------
### Blazor ModalOptions Configuration Reference for Display
Source: https://context7.com/blazored/modal/llms.txt
Details the ModalOptions class used for configuring the appearance and behavior of modals. It covers settings for size, position, animations, styling, and various behavioral aspects like disabling background cancellation and controlling header visibility.
```csharp
public class ModalOptions
{
// Size options
public ModalSize? Size { get; set; } // Small, Medium, Large, ExtraLarge, Custom, Automatic
public string? SizeCustomClass { get; set; } // CSS class when Size = Custom
// Position options
public ModalPosition? Position { get; set; } // TopCenter, TopLeft, TopRight, Middle, BottomLeft, BottomRight, Custom
public string? PositionCustomClass { get; set; } // CSS class when Position = Custom
// Animation options
public ModalAnimationType? AnimationType { get; set; } // FadeInOut, PopInOut, PopIn, None
// Styling options
public string? Class { get; set; } // Custom CSS class for modal
public string? OverlayCustomClass { get; set; } // Custom CSS class for overlay/backdrop
// Behavior options
public bool? DisableBackgroundCancel { get; set; } // Prevent closing by clicking backdrop
public bool? HideHeader { get; set; } // Hide entire modal header
public bool? HideCloseButton { get; set; } // Hide X close button
public bool? UseCustomLayout { get; set; } // Use completely custom HTML structure
public bool? ActivateFocusTrap { get; set; } // Enable keyboard focus trapping for accessibility
}
```
--------------------------------
### Configure Blazored Modal Behavior Options
Source: https://context7.com/blazored/modal/llms.txt
Demonstrates how to control specific behavior options for Blazored Modals, such as close button visibility, background click behavior, header visibility, focus trapping, and custom CSS classes for the modal and overlay. This is achieved by passing a ModalOptions object to the IModalService.Show method.
```razor
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
void ShowModalWithOptions()
{
var options = new ModalOptions
{
HideCloseButton = true, // Hide the X button
DisableBackgroundCancel = true, // Prevent closing by clicking backdrop
HideHeader = false, // Show/hide entire header
ActivateFocusTrap = true, // Enable keyboard focus trapping
UseCustomLayout = false, // Use custom modal HTML structure
Class = "my-custom-modal", // Custom CSS class
OverlayCustomClass = "my-overlay" // Custom overlay CSS class
};
Modal.Show("Custom Options", options);
}
}
```
--------------------------------
### Configure Single Modal Size (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/size.md
Sets the size for an individual modal instance by creating a ModalOptions object and specifying the desired Size. This object is then passed to the Show method of the Modal service. This allows for specific modal sizing independent of global settings.
```csharp
var options = new ModalOptions()
{
Size = ModalSize.Large
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### BlazoredModalInstance API for Modal Control
Source: https://context7.com/blazored/modal/llms.txt
API available within modal components for self-control. Use SetTitle to update the title dynamically and CloseAsync/CancelAsync to close the modal with or without a result payload.
```csharp
public partial class BlazoredModalInstance
{
// Set or update the modal title dynamically
public void SetTitle(string title);
// Close with OK result
public async Task CloseAsync();
public async Task CloseAsync(ModalResult modalResult);
// Close with Cancel result
public async Task CancelAsync();
public async Task CancelAsync(TPayload payload);
}
```
```csharp
// Usage in modal component
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
// Methods
BlazoredModal.SetTitle("New Title");
await BlazoredModal.CloseAsync();
await BlazoredModal.CloseAsync(ModalResult.Ok(myData));
await BlazoredModal.CancelAsync();
await BlazoredModal.CancelAsync(somePayload);
```
--------------------------------
### Configure Modal Size with ModalOptions - Razor
Source: https://context7.com/blazored/modal/llms.txt
Shows how to control modal width using predefined sizes (Small, Medium, Large, ExtraLarge, Automatic) or custom sizes via ModalOptions. The SetSize method applies the selected size, and for custom sizes, a custom CSS class can be specified through SizeCustomClass property.
```razor
@page "/size"
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
void DefaultSize()
{
Modal.Show("Size: Medium (Default)");
}
void SetSize(ModalSize size)
{
var options = new ModalOptions { Size = size };
if (size == ModalSize.Custom)
options.SizeCustomClass = "my-custom-size";
Modal.Show($"Size: {size}", options);
}
}
```
--------------------------------
### Apply Custom Overlay Class to Single Modal (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/styling/custom-overlay.md
This C# code shows how to apply a custom CSS class to a specific Blazored Modal instance. It involves creating a `ModalOptions` object, setting the `OverlayCustomClass` property, and then passing these options when showing the modal.
```csharp
var options = new ModalOptions()
{
OverlayCustomClass = "custom-modal-overlay"
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Configure Single Modal with Custom CSS Classes (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/styling/modal-style.md
Customize the CSS classes for a specific Blazored Modal instance by creating a `ModalOptions` object and setting its `Class` property. This allows for targeted styling of individual modals without affecting others. The options object is then passed to the `Modal.Show` method.
```csharp
var options = new ModalOptions()
{
Class = "my-custom-modal-class"
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Show Bootstrap Modal with Custom Layout in C#
Source: https://github.com/blazored/modal/blob/main/docs/docs/styling/custom-layout.md
This C# code demonstrates how to display a Blazored Modal using a custom layout. It configures `ModalOptions` to enable `UseCustomLayout` and passes parameters to the custom modal component before showing it.
```csharp
var options = new ModalOptions
{
UseCustomLayout = true
};
var parameters = new ModalParameters()
.Add(nameof(BootstrapModal.Message), "Hello Bootstrap modal!!");
Modal.Show("Bootstrap Modal", parameters, options);
```
--------------------------------
### Configure Blazored Modal Animations
Source: https://context7.com/blazored/modal/llms.txt
Demonstrates how to apply different animation styles or disable animations for Blazored Modals. It uses Razor syntax and interacts with the IModalService to show modals with various animation types like Fade-in Fade-Out, Pop-in Pop-Out, Pop-in Fade-Out, and None.
```razor
@page "/animation"
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
void AnimationDefault()
{
Modal.Show("Default Animation");
}
void AnimationPopInOut()
{
var options = new ModalOptions { AnimationType = ModalAnimationType.PopInOut };
Modal.Show("Animation Type: PopInOut", options);
}
void AnimationPopIn()
{
var options = new ModalOptions { AnimationType = ModalAnimationType.PopIn };
Modal.Show("Animation Type: PopIn", options);
}
void NoAnimation()
{
var options = new ModalOptions { AnimationType = ModalAnimationType.None };
Modal.Show("Animation Type: None", options);
}
}
```
--------------------------------
### Configure Single Custom Modal Size (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/size.md
Sets a custom size for a specific modal by using ModalSize.Custom and providing a CSS class name to the SizeCustomClass property within a ModalOptions object. This object is then passed to the Show method, allowing fine-grained control over individual modal dimensions.
```csharp
var options = new ModalOptions()
{
Size = ModalSize.Custom,
SizeCustomClass = "custom-modal"
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Pass Data to Modal Using ModalParameters
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/passing-data.md
Demonstrates how to pass data to a modal component by creating a ModalParameters object and adding values that match the component's parameter names. Uses nameof for strong typing instead of string literals to ensure type safety.
```csharp
var parameters = new ModalParameters()
.Add(nameof(DisplayMessage.Message), "Hello, World!");
Modal.Show("Passing Data", parameters);
```
--------------------------------
### Show Second Modal from First Modal (Razor)
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/multiple-modals.md
This code demonstrates how to display a second modal ('ModalTwo') from within the first modal ('ModalOne'). It also includes functionality to close the first modal after the second modal is closed, showcasing modal lifecycle management.
```razor
Modal One
@code {
[CascadingParameter] BlazoredModalInstance ModalOne { get; set; } = default!;
[CascadingParameter] IModalService ModalService { get; set; } = default!;
private async Task ShowModalTwo()
{
var modalTwo = ModalService.Show("Second Modal");
_ = await modalTwo.Result;
await ModalOne.CloseAsync();
}
private async Task Close() => await ModalOne.CloseAsync();
}
```
--------------------------------
### Return Data from Modal using ModalResult - Razor
Source: https://context7.com/blazored/modal/llms.txt
Demonstrates how to retrieve data from a modal component using the ModalResult object. The parent component shows a modal and captures the returned data if not cancelled, displaying it on the page. The MessageForm component collects user input and returns it via CloseAsync with ModalResult.Ok().
```razor
@page "/returningdata"
@if (!string.IsNullOrWhiteSpace(_message))
{
Your message was:
@_message
}
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
string? _message;
async Task ShowModal()
{
var messageForm = Modal.Show();
var result = await messageForm.Result;
if (!result.Cancelled)
_message = result.Data?.ToString() ?? string.Empty;
}
}
```
```razor
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
string? Message { get; set; }
protected override void OnInitialized()
=> BlazoredModal.SetTitle("Enter a Message");
async Task SubmitForm()
=> await BlazoredModal.CloseAsync(ModalResult.Ok(Message));
async Task Cancel()
=> await BlazoredModal.CancelAsync();
}
```
--------------------------------
### Await Modal Result in Blazor
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/modal-reference.md
This Blazor Razor component demonstrates how to display a modal and wait for its result. It injects the IModalService, shows a modal named 'Movies', and then checks if the modal was cancelled or confirmed.
```razor
@page "/movies"
Movies
@code {
[CascadingParameter] IModalService Modal { get; set; } = default!;
private async Task ShowModal()
{
var moviesModal = Modal.Show("My Movies");
var result = await moviesModal.Result;
if (result.Cancelled)
{
Console.WriteLine("Modal was cancelled");
}
else if (result.Confirmed)
{
Console.WriteLine("Modal was closed");
}
}
}
```
--------------------------------
### Access Returned Data from Blazored Modal (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/returning-data.md
This C# code snippet shows how to invoke a Blazored Modal (`MessageForm`) and asynchronously retrieve the data returned from it. It checks if the modal was confirmed and then accesses the returned data via `result.Data`. This assumes the modal was opened using a Blazored Modal service.
```csharp
var messageForm = Modal.Show();
var result = await messageForm.Result;
if (result.Confirmed)
{
_message = result.Data.ToString();
}
```
--------------------------------
### Set Global Blazored Modal Options in Routes.razor
Source: https://context7.com/blazored/modal/llms.txt
Configures default options for all modals within the application by using the CascadingBlazoredModal component in Routes.razor. This allows setting global properties like size, position, animation type, close button visibility, background cancel behavior, and focus trap activation.
```razor
```
--------------------------------
### Configure Modal Position in Viewport - Razor
Source: https://context7.com/blazored/modal/llms.txt
Demonstrates positioning modals at different viewport locations using ModalOptions Position property with predefined positions (TopCenter, TopLeft, TopRight, Middle, BottomLeft, BottomRight) or custom positions. Custom positions require specifying a custom CSS class via PositionCustomClass.
```razor
@page "/position"
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
void PositionCenter()
{
Modal.Show("Top Center Modal (Default)");
}
void PositionCustom(ModalPosition position)
{
var options = new ModalOptions { Position = position };
if (position == ModalPosition.Custom)
options.PositionCustomClass = "my-custom-position";
Modal.Show($"Position: {position}", options);
}
}
```
--------------------------------
### Create Razor Component with Parameter for Modal Display
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/passing-data.md
Defines a Blazor component that accepts a Message parameter and displays it in the modal. The component includes a CascadingParameter for BlazoredModalInstance to enable closing the modal. This component will be displayed within the Blazored Modal.
```razor
@Message
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
[Parameter] public string? Message { get; set; }
private async Task Close() => await BlazoredModal.CloseAsync();
}
```
--------------------------------
### Configure Blazored Modal Custom Position for Single Modal (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/position.md
Configure a single Blazored Modal instance to use a custom position by setting `Position` to `ModalPosition.Custom` and providing a CSS class to `PositionCustomClass` within `ModalOptions`. This allows for specific modal positioning via CSS.
```csharp
var options = new ModalOptions()
{
Position = ModalPosition.Custom,
PositionCustomClass = "custom-modal-position"
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Modal Component Receiving Parameters (Razor)
Source: https://context7.com/blazored/modal/llms.txt
A Blazor component designed to receive parameters, specifically a 'Message' in this case. It displays the passed message and provides buttons to close the modal after submission or cancellation. The `[Parameter]` attribute is used to define incoming data.
```razor
@Message
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
[Parameter] public string? Message { get; set; }
async Task SubmitForm() => await BlazoredModal.CloseAsync();
async Task Cancel() => await BlazoredModal.CancelAsync();
}
```
--------------------------------
### Modal Component with Close/Cancel Actions (Razor)
Source: https://context7.com/blazored/modal/llms.txt
A Blazor component designed to be used as a modal. It provides buttons to close the modal with a result or cancel it, utilizing the `BlazoredModalInstance` and `ModalResult` for interaction.
```razor
Please click one of the buttons below to close or cancel the modal.
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
async Task Close() => await BlazoredModal.CloseAsync(ModalResult.Ok(true));
async Task Cancel() => await BlazoredModal.CancelAsync();
}
```
--------------------------------
### Handle Complex Modal Results with UserData in Blazor
Source: https://context7.com/blazored/modal/llms.txt
Demonstrates how to show a modal that returns complex data, specifically a UserData object. It shows how to pass initial parameters, await the modal result, check if it was confirmed, and cast the returned data to the expected type. This involves a parent component and a UserForm component.
```razor
@code {
[CascadingParameter] public IModalService Modal { get; set; } = default!;
public class UserData
{
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
async Task ShowUserForm()
{
var parameters = new ModalParameters
{
{ "InitialName", "John Doe" }
};
var modalRef = Modal.Show("Edit User", parameters);
var result = await modalRef.Result;
if (result.Confirmed) // Same as !result.Cancelled
{
if (result.Data is UserData userData)
{
Console.WriteLine($"Name: {userData.Name}, Email: {userData.Email}");
}
}
}
}
```
```razor
@code {
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
[Parameter] public string InitialName { get; set; } = "";
private string Name { get; set; } = "";
private string Email { get; set; } = "";
protected override void OnInitialized()
{
Name = InitialName;
}
async Task Save()
{
var userData = new UserData
{
Name = Name,
Email = Email
};
await BlazoredModal.CloseAsync(ModalResult.Ok(userData));
}
async Task Cancel()
{
await BlazoredModal.CancelAsync();
}
}
```
--------------------------------
### Hide Blazored Modal Header for a Single Instance (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/hide-header.md
Show a single Blazored Modal instance without its default header by creating a `ModalOptions` object and setting its `HideHeader` property to `true`. This option is then passed when showing the modal.
```csharp
var options = new ModalOptions()
{
HideHeader = true
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Blazored ModalResult API
Source: https://context7.com/blazored/modal/llms.txt
Represents the result returned when a modal closes. It includes properties for the returned data, its type, and whether the modal was cancelled or confirmed. Static factory methods simplify creating result instances.
```csharp
public class ModalResult
{
public object? Data { get; } // Data returned from modal
public Type? DataType { get; } // Type of returned data
public bool Cancelled { get; } // True if modal was cancelled
public bool Confirmed { get; } // True if modal was confirmed (!Cancelled)
// Static factory methods
public static ModalResult Ok(); // Confirmed with no data
public static ModalResult Ok(T result); // Confirmed with data
public static ModalResult Cancel(); // Cancelled with no data
public static ModalResult Cancel(T payload); // Cancelled with data
}
```
--------------------------------
### Configure Global Modal Size (Razor)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/size.md
Sets the default size for all modals in the application by configuring the Size parameter on the CascadingBlazoredModal component. This is useful for maintaining a consistent modal appearance throughout your Blazor application.
```razor
```
--------------------------------
### Define Custom Overlay CSS Class
Source: https://github.com/blazored/modal/blob/main/docs/docs/styling/custom-overlay.md
This CSS code defines a custom class 'custom-modal-overlay' that sets a semi-transparent red background for the modal overlay. The `!important` flag may be necessary to override Blazored Modal's default scoped CSS.
```css
.custom-modal-overlay {
background-color: rgba(255, 0, 0, 0.5) !important;
}
```
--------------------------------
### Submit Message Data from Blazored Modal (Razor)
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/returning-data.md
This Razor component, `MessageForm.razor`, allows users to enter a message and submit it. It uses Blazored Modal's `ModalResult.Ok` to return the entered message when the form is submitted, or cancels the modal if the cancel button is clicked. It depends on Blazored Modal for modal functionality.
```razor
@code {
private readonly Form _form = new();
[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;
protected override void OnInitialized() => BlazoredModal.SetTitle("Enter a Message");
private async Task SubmitForm() => await BlazoredModal.CloseAsync(ModalResult.Ok(_form.Message));
private async Task Cancel() => await BlazoredModal.CancelAsync();
}
```
--------------------------------
### Configure Blazored Modal Custom Position Globally (Razor)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/position.md
Configure Blazored Modal to use a custom position for all modals by setting `Position` to `ModalPosition.Custom` and providing a CSS class to `PositionCustomClass` in the `CascadingBlazoredModal` component.
```razor
```
--------------------------------
### Configure Single Modal to Hide Close Button (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/configuration/close-button.md
Configure a specific Blazored Modal instance to hide its close button by creating a ModalOptions object and setting HideCloseButton to true. This option is then passed when showing the modal.
```csharp
var options = new ModalOptions()
{
HideCloseButton = true
};
Modal.Show("Are you sure?", options);
```
--------------------------------
### Close Second Modal (C#)
Source: https://github.com/blazored/modal/blob/main/docs/docs/usage/multiple-modals.md
This snippet defines the 'ModalTwo' component, which contains a simple button to close itself. It interacts with the Blazored ModalInstance to handle its own closure.
```csharp