Adding Bootstrap Modal Popup in MVC: A Step-by-Step Guide

How to add bootstrap modal popup in mvc

To add a Bootstrap modal popup in an MVC (Model-View-Controller) application, follow these steps:

  1. Add Bootstrap to your project: Download the Bootstrap library and add the necessary files (CSS and JS) to your project.
  2. Create a new View: Create a new View in your MVC project that will contain the modal popup.
  3. Add HTML for the modal: Add the HTML code for the modal popup to your new View. This typically includes a button or link that triggers the modal, and the modal itself (with a header, body, and footer).
  4. Add JavaScript to show/hide the modal: Add JavaScript code to show and hide the modal when the button or link is clicked. This typically involves using the jQuery library to add a click event listener to the button or link, and then showing/hiding the modal using the Bootstrap JavaScript API.

Here’s some sample code to get you started:

<!-- HTML for the modal popup -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Modal Title</h4>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        Modal content goes here.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

<!-- Button to trigger the modal popup -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch modal
</button>

<!-- JavaScript to show/hide the modal popup -->
<script>
  $(document).ready(function() {
    $('#myModal').on('shown.bs.modal', function() {
      $('#myInput').trigger('focus')
    })
  });
</script>

This code creates a modal popup with a title, body, and footer, and a button to launch the modal. The JavaScript code uses jQuery to show/hide the modal when the button is clicked.

 

Similar Posts