-
Create a Partial View for the Modal: Create a partial view named
_ConfirmationModal.cshtml
that contains the HTML for your confirmation modal:<!-- _ConfirmationModal.cshtml --> <div id="confirmationModal" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Confirmation</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <p id="confirmationMessage"></p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary" id="confirmButton">Confirm</button> </div> </div> </div> </div>
-
Add JavaScript to Show Modal and Handle Confirmation: Add JavaScript to show the modal and handle the user's confirmation. You can include this script in your layout file so it's available on all pages:
<script> function showConfirmationModal(message, confirmCallback) { $('#confirmationMessage').text(message); $('#confirmationModal').modal('show'); $('#confirmButton').off('click').on('click', function() { $('#confirmationModal').modal('hide'); if (confirmCallback) { confirmCallback(); } }); } </script>
-
Use the Modal in Your Views: You can use the
showConfirmationModal
function from anywhere in your views or scripts to display the confirmation modal. For example:<button onclick="showConfirmationModal('Are you sure you want to delete this item?', function() { deleteItem(); })">Delete</button>
With these steps, you have a reusable confirmation modal that can be used from any page in your ASP.NET MVC or ASP.NET Razor Pages application.