Search code examples
c#modal-dialogblazorblazored

Blazored Modals do not seem to open


I've followed this guide: https://github.com/Blazored/Modal. (Currently I have installed latest stable Package - 5.0.2). I went through these steps:

  1. Installed the Package
  2. Added imports
  3. Changed the CascadingBlazoredModal
  4. Added both the references in _host
  5. Changed Index.razor to the following code:
@page "/"
@inject IModalService Modal

<h1>Hello, world!</h1>

Welcome to Blazored Modal.

<button @onclick="@(() => Modal.Show<FetchData>("Fetched data"))" class="btn btn-primary">Fetched data</button>

I've tried several different solutions (including: switching browser, using only bootstrap) - nothing seems to work.

I have noticed an odd thing - none of the other buttons seem to work (they are clickable, but no action is done), so that may be a clue to solving this bug.

I would be also glad if someone could help me out with a simple div that looks like a Modal popup as that would make things much easier.


Solution

  • The bootstrap modal depends on java script manipulating css classes and styles directly on the element. I quickly knocked this up to show how Blazer can be used to manipulate the same classes it is not complete.

    Modal.razor

    <button class="btn btn-primary"  @onclick="ToggleModal">
        Launch demo modal
    </button>
    
    <div class="@modalClass" tabindex="-1" style="display: @displayMode;" >
        <div class="modal-dialog" >
           <div class="modal-content" >
                <div class="modal-header" >
                    <h5 class="modal-title" >Modal title</h5>
                    <button class="close" @onclick="ToggleModal" aria-label="Close" >
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    @ChildContent
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary"  @onclick="ToggleModal">Close</button>
                    <button class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    
    
    @code {
    
        bool open = false;
        string modalClass => open ? "modal fade show" : "modal fade";
        string displayMode => open ? "block" : "none";
    
    
        private void ToggleModal()
        {
            open = !open;       
            StateHasChanged();
        }
    
        [Parameter]
        public RenderFragment ChildContent { get; set; }
    }