Modal

by Blazored

Blazored / Modal

A powerful and customizable modal implementation for Blazor applications.

314 Stars 78 Forks Last release: about 1 month ago (v5.1.0) MIT License 248 Commits 9 Releases

Available items

No Items, yet!

The developer of this repository has not created any items for sale yet. Need a bug fixed? Help with integration? A different license? Create a request here:

Blazored Modal

A powerful and customizable modal implementation for Blazor applications.

Build Status

Nuget

Screenshot of the component in action

Getting Setup

You can install the package via the nuget package manager just search for Blazored.Modal. You can also install via powershell using the following command.

Install-Package Blazored.Modal

Or via the dotnet CLI.

dotnet add package Blazored.Modal

Internet Explorer 11

This package can be used with Internet Explorer 11, but some special care should to be taken.

  • Only Blazor Server works with IE11. Blazor WebAssembly does not work with any IE version. See this
  • A polyfill is necessary for this component to work. See this page for an explanation on how to install and use it. The sample project for Blazor Server uses the polyfill and thus should work on IE11
  • V4.2.0 or higher of
    Blazored.Modal
    should be used for correct CSS in IE11

Taking these things into account,

Blazored.Modal
should work on IE11.

Please note: When upgrading from v4 to v5 you must remove the
 tag from your 
MainLayout
component.

1. Register Services

For Blazor Server: You will need to add the following using statement and add a call to register the Blazored Modal services in your applications

Startup.ConfigureServices
method.
using Blazored.Modal;

public void ConfigureServices(IServiceCollection services) { services.AddBlazoredModal(); }

For Blazor WebAssembly: You will need to add the following using statement and add a call to register the Blazored Modal services in your applications

Program.Main
method.
using Blazored.Modal;

public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add("app");

builder.Services.AddBlazoredModal();

await builder.Build().RunAsync();

}

2. Add Imports

Add the following to your _Imports.razor

@using Blazored.Modal
@using Blazored.Modal.Services

3. Add CascadingBlazoredModal Component

Add the

 component into your applications App.razor, wrapping the Router as per the example below.
    
        
            
        
        
            

Page not found

Sorry, but there's nothing here!

4. Add reference to style sheet & javascript reference

Add the following line to the

head
tag of your
_Host.cshtml
(Blazor Server) or
index.html
(Blazor WebAssembly).

Then add a reference to the Blazored Modal JavaScript file at the bottom of the respective page after the reference to the Blazor file.


Usage

Please checkout the sample projects in this repo to see working examples of the features in the modal.

Displaying the modal

In order to show a modal, you need to inject the

IModalService
into the component or service you want to invoke the modal. You can then call the
Show
method passing in the title for the modal and the type of the component you want the modal to display.

For example, if I have a component called

Movies
which I want to display in the modal and I want to call it from the
Index
component on a button click.
@page "/"
@inject IModalService Modal

Hello, world!

Welcome to Blazored Modal.

Modal.Show("My Movies"))" class="btn btn-primary">View Movies

Passing Parameters

If you want to pass values to the component you're displaying in the modal, then you can use the

ModalParameters
object. The name you provide must match the name of a parameter defined on the component being displayed.

Index Component

@page "/"

My Movies

    @foreach (var movie in Movies) {
  • @movie.Name (@movie.Year) - ShowEditMovie(movie.Id))" class="btn btn-primary">Edit Movie

  • }

@code {

[CascadingParameter] public IModalService Modal { get; set; }

List<movies> Movies { get; set; }

void ShowEditMovie(int movieId)
{
    var parameters = new ModalParameters();
    parameters.Add(nameof(EditMovie.MovieId), movieId);

    Modal.Show<editmovie>("Edit Movie", parameters);
}

}

EditMovie Component

@inject IMovieService MovieService

<div class="form-group">
    <label for="movie-name">Movie Name</label>
    <input type="text" class="form-control" id="movie-name">
</div>

<div class="form-group">
    <label for="year">Year</label>
    <input type="text" class="form-control" id="year">
</div>

<button class="btn btn-primary">Submit</button>
<button class="btn btn-secondary">Cancel</button>

@code {

[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; }

[Parameter] public int MovieId { get; set; }

Movie Movie { get; set; }

protected override void OnInitialized()
{
    Movie = MovieService.Load(MovieId);
}

void SaveMovie()
{
    MovieService.Save(Movie);
    BlazoredModal.Close(ModalResult.Ok<movie>(Movie));
}

}

Modal Reference

When you open a modal you can capture a reference to it and await the result of that modal. This is useful when you want to perform an action when a modal is closed or cancelled.

@page "/"

My Movies

View Movies

@code {

[CascadingParameter] public IModalService Modal { get; set; }

async Task ShowModal()
{
    var moviesModal = Modal.Show<movies>("My Movies");
    var result = await moviesModal.Result;

    if (result.Cancelled)
    {
        Console.WriteLine("Modal was cancelled");
    }
    else
    {
        Console.WriteLine("Modal was closed");
    }
}

}

Returning objects back to the calling code

It is common to want to return messages or objects back from a modal to the calling code. This is achieved using the

ModalResult
class.

In the example below, when the form is submitted a

ModalResult.Ok
containing the string "Form was submitted successfully." will be returned back to the calling code. If it is cancelled a
ModalResult.Cancelled
will be returned.
<div class="form-group">
    <label for="first-name">First Name</label>
    <input type="text" class="form-control" id="first-name" placeholder="Enter First Name">
</div>

<div class="form-group">
    <label for="last-name">Last Name</label>
    <input type="text" class="form-control" id="last-name" placeholder="Enter Last Name">
</div>

<button class="btn btn-primary">Submit</button>
<button class="btn btn-secondary">Cancel</button>

@code {

[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; }

bool ShowForm { get; set; } = true;
string FirstName { get; set; }
string LastName { get; set; }
int FormId { get; set; }

void SubmitForm()
{
    BlazoredModal.Close(ModalResult.Ok($"Form was submitted successfully."));
}

void Cancel()
{
    BlazoredModal.Cancel();
}

}

Below is the caller for the component above. When the result is returned the string set in the

Ok
method can be access via the
Data
property on the
ModalResult
.
@page "/"

View Form

@code {

[CascadingParameter] public IModalService Modal { get; set; }

async Task ShowModal()
{
    var formModal = Modal.Show<signupform>("Please SignUp");
    var result = await formModal.Result;

    if (result.Cancelled)
    {
        Console.WriteLine("Modal was cancelled");
    }
    else
    {
        Console.WriteLine(result.Data);
    }
}

}

The example above is only using a string value but you can also pass complex objects back as well.

Customizing the modal

The modals can be customized to fit a wide variety of uses. These options can be set globally or changed programatically on a per modal basis.

Hiding the close button

A modal has a close button in the top right hand corner by default. The close button can be hidden by using the

HideCloseButton
parameter:



Or in the

Modal.Show()
method:
@code {
    void ShowModal()
    {
        var options = new ModalOptions()
        {
            HideCloseButton = false
        };

    Modal.Show<movies>("My Movies", options);
}

}

Disabling background click cancellation

You can disable cancelling the modal by clicking on the background using the

DisableBackgroundCancel
parameter.



Or in the

Modal.Show()
method:
@code {
    void ShowModal()
    {
        var options = new ModalOptions()
        {
            DisableBackgroundCancel = true
        };

    Modal.Show<movies>("My Movies", options);
}

}

Styling the modal

You can set an alternative CSS style for the modal if you want to customize the look and feel. This is useful when your web application requires different kinds of modals, like a warning, confirmation or an input form.

Use the

Class
parameter to set the custom styling globally:



Or in the

Modal.Show()
method:
@code {
    void ShowModal()
    {
        var options = new ModalOptions()
        {
            Class = "blazored-modal-movies"
        };

    Modal.Show<movies>("My Movies", options);
}

}

Setting the position

Modals are shown in the center of the viewport by default. The modal can be shown in different positions if needed.

The following positions are available out of the box:

ModalPosition.Center
,
ModalPosition.TopLeft
,
ModalPosition.TopRight
,
ModalPosition.BottomLeft
and
ModalPosition.BottomRight
.

Use the

Position
parameter to set the position globally:



Or in the

Modal.Show()
method:
@code {
    void ShowModal()
    {
        var options = new ModalOptions()
        {
            Position = "ModalPosition.BottomLeft"
        };

    Modal.Show<movies>("My Movies", options);
}

}

If you need to use a custom position use

ModalPosition.Custom
and set the CSS class to use in
PositionCustomClass
.
@code {
    void ShowModal()
    {
        var options = new ModalOptions()
        {
            Position = ModalPosition.Custom
            PositionCustomClass = "custom-position-class";
        };
        Modal.Show("My Movies", options);
    }
}

Animation

The modal also supports some animations.

The following animation types are available out of the box:

ModalAnimation.FadeIn
,
ModalAnimation.FadeOut
and
ModalAnimation.FadeInOut
.

Use the

Animation
parameter to set the custom styling globally:



Or in the

Modal.Show()
method:
@code {
    void ShowModal()
    {
        var options = new ModalOptions() 
        { 
            Animation = ModalAnimation.FadeInOut(1)
        };

    Modal.Show<movies>("My Movies", options);
}

}

Multiple Modals

It's possible to have multiple active modal instances at a time. You can find a working example of this in the sample projects but here is some sample code.

Below is a component which being displayed inside a Blazored Modal instance. When a user clicks on the Delete button the

Yes
method is invoked and creates a new modal instance.
@inject IModalService ModalService

Are you sure you want to delete the record?
<button class="btn btn-outline-danger">Delete</button>
<button class="btn btn-primary">Cancel</button>

@code {

[CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; }

async Task Yes()
{
    var confirmationModal = ModalService.Show<confirmationprompt>();
    var result = await confirmationModal.Result;

    if (result.Cancelled)
        return;

    BlazoredModal.Close(ModalResult.Ok($"The user said 'Yes'"));
}

void No()
{
    BlazoredModal.Close(ModalResult.Cancel());
}

}

We use cookies. If you continue to browse the site, you agree to the use of cookies. For more information on our use of cookies please see our Privacy Policy.