How to display a partial view as a popup/modal on button click using bootstrap or jquery?

▼魔方 西西 提交于 2019-12-05 11:56:23

Your button reference a button to toggle showing/hiding of the modal, data-target="#myModal", but your modal didn't have an id.

It's not clear if you want the whole modal to be a partial, or just the inner content. It doesn't matter at all though, since this is all applied server-side, and your modal is processed client-side.

Actually, bootstrap already have support for dynamically loading "partials" (using jQuery load in code behind):

<button class="btn btn-primary" href="myFile.html" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>

The above is a much simpler way than my example below..

Read more about jQuery load() or get()

var myData = '<div class="modal-dialog">' +
  '<div class="modal-content">' +
  '<div class="modal-header">' +
  '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>' +
  '</button>' +
  '<h4 class="modal-title">Modal title</h4>' +
  '</div>' +
  '<div class="modal-body">' +
  '<p>Load on request</p>' +
  '</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>';

//myData could be a file, with the same contents, and then you would use the ".load()" method below instead
$('#myModal').on('show.bs.modal', function(e) {
  //$('#myModal').load('myFile.cshtml'); //When loading from a file/url
  $('#myModal').html(myData); //loading from a string
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Launch demo modal</button>

<div class="modal" id="myModal">

</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!