MVC 5 Bootstrap Modal not working

12,796

To show the modal, you need to use javascript/jquery.

You're instead using an ActionLink which will redirect your browser to the url in the action link - in this case a partial (ie a view without _layout, so no css/js) (ie exactly what you're seeing).

What you need is:

  • user clicks link/button
  • optional: ajax loads the content of the partial into the modal
  • jquery shows the modal

This answer shows the jquery needed.

In your case, simply remove this:

@Html.ActionLink("Test Modal ", "ViewSampleModal", "Admin", null, new { @class = "modal-link btn-xs btn-success" })

and replace with

<a class='modal-link btn-xs btn-success'>Test Modal</a>

and

$(".modal-link").click(function() {
    $('#myModal').modal('show');
});

or

$(".modal-link").click(function() {
    $("#myModal .modal-body").load(
       '@Url.Action("ViewSampleModal", "Admin")',
       function() {       
           $('#myModal').modal('show');
       });
});

this last part will only work if in a .cshtml file, it will not work if in a .js file (as @Url.Action won't run server-side).

Share:
12,796
Caverman
Author by

Caverman

Updated on June 26, 2022

Comments

  • Caverman
    Caverman almost 2 years

    I’m still in the MVC learning mode and one of the things I need is a Delete Confirmation modal and I would like to use Bootstrap to do that. I’ve searched around and came up with some examples that I’ve looked over a few times but I can’t seem to get it to work.

    I made sure I had the latest version of Bootstap (v3.3.5) downloaded and in my Content folder. I know Bootstrap and the site can see it because the layout of my buttons and grid all seem to be styled correctly.

    However using the sample code below when I click on my “Test Modal” button it doesn’t open a modal. It just displays the partial view without any CSS/Bootstrap styling. Also the cancel button and save button inside the modal aren’t firing off any code. I’m curious if anyone sees what I’m doing wrong or has any suggestions on how I can figure out the issue.

    This is in the section of my _Layout.cshtml page.

    <style>
            .modal-content {
                width: 600px !important;
                margin: 30px auto !important;
            }
        </style>
    
        <script type="text/javascript">
            $(function () {
                // Initalize modal dialog
                // attach modal-container bootstrap attributes to links with .modal-link class.
                // when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
                $('body').on('click', '.modal-link', function (e) {
                    e.preventDefault();
                    $(this).attr('data-target', '#modal-container');
                    $(this).attr('data-toggle', 'modal');
                });
    
                // Attach listener to .modal-close-btn's so that when the button is pressed the modal dialog disappears
                $('body').on('click', '.modal-close-btn', function () {
                    $('#modal-container').modal('hide');
                });
    
                //clear modal cache, so that new content can be loaded
                $('#modal-container').on('hidden.bs.modal', function () {
                    $(this).removeData('bs.modal');
                });
    
                $('#CancelModal').on('click', function () {
                    return false;
                });
            });
        </script>
    

    This is in the section of my _Layout.cshtml page.

    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title" id="myModalLabel">Delete Example</h4>
                    </div>
                    <div class="modal-body">
                        Are you sure you wish to delete this item?
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="button" id="mySubmit" class="btn btn-primary">Confirm</button>
                    </div>
                </div>
            </div>
        </div>
    

    This is the link I’m using in my Index.cshtml page.

    @Html.ActionLink("Test Modal ", "ViewSampleModal", "Admin", null, new { @class = "modal-link btn-xs btn-success" })
    

    This is in my AdminController.

    [HttpGet]
            public ActionResult ViewSampleModal()
            {
                return PartialView("_SampleModal");
            }
    [HttpPost]
        public ActionResult ModalClick()
        {
            return RedirectToAction("Index");
        }
    

    This is my _SampleModal.cshtml.

    <div class="modal-body">
        <div class="alert alert-warning">
            <span class="glyphicon glyphicon-warning-sign"></span>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec consequat nisl a nibh tincidunt condimentum. Nullam in augue vitae augue dictum eleifend. Nunc porta fermentum metus, quis efficitur lectus scelerisque ac. Quisque egestas sit amet nunc in interdum. Etiam malesuada maximus nisi, id tempus metus. Vivamus at sapien ut metus aliquet sodales sed id magna. Integer in auctor ex. Phasellus tempor, est vel placerat dapibus, nulla dui tempor ligula, at pulvinar libero nunc gravida metus. Proin non feugiat felis. Proin ut ultrices ex. Morbi aliquet lacinia elit at bibendum. Nunc facilisis, neque a finibus dignissim, turpis felis vulputate diam, a tristique tellus nibh nec nulla. Suspendisse eget augue non turpis dignissim euismod eget eget odio. Donec sit amet nibh cursus, efficitur nibh in, sodales arcu. Pellentesque pulvinar consequat lacus ac porttitor.
        </div>
    
        @using (Html.BeginForm("ModalClick", "Admin", FormMethod.Post))
        {
            <div class="row">
                &nbsp;
            </div>
            <div class="row">
                <div class="col-md-4 col-md-offset-4">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                    <button type="submit" id="approve-btn" class="btn btn-danger">Save</button>
                </div>
            </div>
        }
    </div>
    
    
    <script type="text/javascript">
        $(function () {
            $('#approve-btn').click(function () {
                $('#modal-container').modal('hide');
            });
        });
    </script>