ASP.NET MVC Core Modal


Do you need to add a simple modal dialog box to your ASP.NET Core MVC project? A modal dialog is a pop-up box that must be dealt with by the user before they can return back to the functionality of the application. Often they are used for important messages that the user needs to acknowledge.

This post has basic modal code for setting up a modal dialog box on your project.

On your page you will add the following code. Here I’m running Bootstrap 4. Feel free to use this code in your own projects.

<h3>Index</h3>
<button id="myClickMeForModalButton" class="btn btn-primary" data-target="myModal" data-toggle="modal">Click Me For Modal</button>
<div class="modal fade" id="myModal">
    <div class="modal-dialog modal-sm"> @* modal-sm modal-lg *@
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">ModalTitle</h4>
                <button type="button" class="close" data-dismiss="modal">x</button>
            </div>
            <div class="modal-body">
                <p>There could be a form right here...</p>
                <p>The focus is on the X so if user presses enter the modal just closes.</p>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary">DoIt</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        $("#myClickMeForModalButton").click(function () {
            $("#myModal").modal('show');
        });
        $("#myClickMeForModalButton").click(function () {
            $("#myModal").modal('hide');
        });
    });
</script>

Below is what the modal looks like after you click the button shown in the screenshot in the above screenshot.