模态形式显示不是模态

问题描述

新来的。我有 Index.cshtml,其中标签如下所示,通过按钮调用 _ModalFormSample.cshtml。

 @{
       ViewBag.Title = "Home Page";
  }
 <div class="row">
     <div class="col-md-4">
        <div class="btn-group" role="group" aria-label="..." style="padding-bottom: 15px;">
            <a href="@Url.Action("ModalFormSample","Home",new {timeStamp = DateTime.UtcNow.ToString()})" class="btn btn-info showModal">Add Account</a>
        </div>
     </div>
 </div>

_ModalFormSample.cshtml

<div class="modal" id="modalFormSample" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                     <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Modal body text goes here.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary">Save changes</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

我希望 _ModalFormSample 在单击“添加帐户”按钮时显示为模态表单,但它没有。

在这里错过了什么?我使用的是 VS 2019 C#.Net

解决方法

由于您想动态显示 modal,您需要编写 js 代码来实现您想要的。

  1. 添加一个 div,您可以在其中附加预期模式的响应 div。在这里,我添加了 ID 为 myModal 的 div。
  2. 编写.showModal点击事件函数如下。评论中有解释。

// showModal button click event
$(".showModal").click(function(e) {

  // to stop redirecting to href url
  e.preventDefault();

  // fetch url from href
  let url = $(this).attr("href");

  // do ajax call and append response in myModal div.
  $.ajax({
    url: url,success: function(response) {
      // Append response in myModal div
      $('#myModal').html(response);
      // show modal
      $('#modalFormSample').modal('show');
    },dataType: "html"
  });
});
<div class="row">
  <div class="col-md-4">
    <div class="btn-group" role="group" aria-label="..." style="padding-bottom: 15px;">
      <a href="@Url.Action(" ModalFormSample ","Home ",new {timeStamp = DateTime.UtcNow.ToString()})" class="btn btn-info showModal">Add Account</a>
    </div>
  </div>
</div>
<div id="myModal"></div>