Bootstrap Modal无法用于用户控制

时间:2016-01-21 15:54:48

标签: asp.net user-controls bootstrap-modal

我有一个ASP.NET网页,可以创建一系列具有不同数据的用户控件。每个用户控件都使用Bootstrap 3模态控件来获得更好的用户体验。我已经仔细检查了所有标签的格式是否正确。页面上的某些模态可以工作,但用户控件中的模态不起作用。

1 个答案:

答案 0 :(得分:0)

使用runat="server"的ASP服务器控件在提供给客户端时将收到唯一的客户端ID。这意味着使用runat="server"属性的任何模态对话框都可能会丢失与使用data-target切换模态的元素的连接。

例如,您的代码可能如下所示:

<button type="button" data-target="#modOverlay" id="btnShowOverlay" runat="server" class="btn btn-success btn-lg" data-toggle="modal">Show Modal</button>
<div class="modal fade" role="dialog" id="modOverlay" runat="server">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        Some Modal
      </div>
      <div class="modal-body">
        Some Info/Data
      </div>
    </div>
  </div>
</div>

如果上面的代码放在用户控件中,则按钮和模态对话框ID都会因runat="server"而改变。

请注意,在用户控件中使用模式会导致类似的问题。如果在单个页面中使用相同构建的多个用户控件,则data-target可以重叠。通常,将使用要处理的第一个对话框。这意味着如果您在对话框中有服务器控件(如按钮),则可能会遇到单击错误服务器按钮的问题。

修复

这是我对此问题的解决方法。请注意,只有当针对模态的按钮(或任何控件)位于同一控件层(即用户控件,网页)内时,这才有效。

// Fix all dynamically generated controls' modal buttons
$(document).ready(function () { // Wait for the page to load all controls
  var fix_modals = $("button[data-toggle='modal'][data-target]"); // Get all <button> elements that target a modal
  for (var len = fix_modals.length, n = 0; n < len; n++) {
    var el = $('[id=' + fix_modals[n].id.slice(0,fix_modals[n].id.lastIndexOf("_") + 1) + fix_modals[n].getAttribute("data-target").slice(1) + ']'); // Try to find the modal using the button's data-target value and its own control prefix
    if (el != undefined) { // Verify that we found a control
      if (el.attr("role") == "dialog") { // verify that the control is a dialog
        fix_modals[n].setAttribute("data-target", "#" + el.attr("id")); // Fix the button's data-target to the client id
      }
    }
  }
});
相关问题