Lakhae
Lakhae

Reputation: 1899

How to load bootstrap modal content via AJAX in MVC?

I am trying to load the contents of the modal using AJAX. Here is the code snippet what I am trying to do.

Index.cshtml

<button type="submit" class="btn btn-default" onclick="Create()">Create</button>

index.js

function AddTask() {
   $Modal = $('#myModal')
   $.get('/Customer/Create', function (data) {
      $Modal.modal({ show: true });
   });
}

Customer Controller

public ActionResult Create()
{
   return PartialView();
}

Create.cshtml

<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <p>My modal content here…</p>
    </div>
    <div class="modal-footer">
        <button class="btn" data-dismiss="modal">Close</button>
    </div>
</div>

How can I load the Create.cshtml contents in the modal?

Upvotes: 2

Views: 3037

Answers (2)

unique
unique

Reputation: 5562

You can do like this. Suppose We get partial view for modal content.Instead of get method

function AddTask() {
   $Modal = $('#myModal');
   $Modal.load('/Customer/Create');
   $Modal.modal('show');
}

Note: Here i used bootstrap 2.3.2.I hope you can get idea of this.

Upvotes: 1

Robert McKee
Robert McKee

Reputation: 21477

I believe the following should work for you, although, I'm not sure about the type="submit"

<button type="submit" href="@Url.Action("Create","Customer")"
  class="btn btn-default" data-toggle="modal" data-target="#myModal">Create</button>

or

<button type="submit" data-remote="@Url.Action("Create","Customer")"
  class="btn btn-default" data-toggle="modal" data-target="#myModal">Create</button>

Although, this has been depreciated, so you'll need to do it manually in version 4 (or write your own extension to handle this like it did in 3.x)

I believe you'll also need to remove <div id="myModal" class="modal hide fade" tabindex="-1" role="dialog"> and the last </div> from Create.cshtml, as these belong in your parent page (Index.cshtml).

Upvotes: 1

Related Questions