Search code examples
twitter-bootstrapmodal-dialogblazorwebassembly

How to close a bootstrap Modal from a blazor webassembly component code?


I was trying to find a way to close a bootstrap modal from a C# method inside a blazor webassembly component.

Bellow is a solution I came up with. It involves the use of IJSRuntime to call a javascript method to manipulate the bootstrap modal. I'm sure there are other ways to solve this.


Solution

  • The bootstrap modal can be closed via javascript:

    Create a javascript wwwroot/js/site.js file with the code:

    export function CloseModal(modalId) {
        $(modalId).modal('hide');
    }
    

    Include the script in index.html at the end of the body:

    ...
    <script src="js/site.js"></script>
    </body>
    

    There exists a parent component calling the modal:

    ParentComponent.razor

    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
      Launch demo modal
    </button>
    
    <ModalComponent />
    
    @code {
    
    }
    

    Then there is a modal component containing the modal: (We are making use of IJSRuntime to call js from C# code)

    ModalComponent.razor

    @inject IJSRuntime js
    
    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>
    
    @code {
    
        IJSObjectReference JsObjectRef { get; set; }
        protected override async Task OnAfterRenderAsync(bool first)
        {
            JsObjectRef = await js.InvokeAsync<IJSObjectReference>("import", "/js/site.js");
        }
        
        async Task SomeMethod(){
         
        //some logic
    
        //call the js function to close the modal
        await JsObjectRef.InvokeVoidAsync("CloseModal", "#exampleModal");
    
    
        }
    }
    

    Now the modal can be closed from the c# code, say for example when a submit method is called.

    This logic has worked for me. I'm sure there are other better solutions for this out there, nevertheless I really hope it helps anyone in need.

    Peace