You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

升级ASP.NET MVC至最新Bootstrap/jQuery后模态框加载局部视图报错

解决ASP.NET MVC升级Bootstrap和jQuery后模态框加载局部视图的Illegal invocation错误

问题原因

升级到最新版Bootstrap(5.x+)后,模态框采用原生JavaScript实现。你同时在<a>标签上使用data-bs-toggle="modal"(Bootstrap原生触发逻辑)和自定义jQuery click事件加载内容,两者的DOM操作逻辑冲突,导致selector-engine.js抛出Uncaught TypeError: Illegal invocation错误,直接阻止了模态框加载。

解决方案

  1. 移除<a>标签上的data-bs-toggle="modal"属性,避免Bootstrap自动触发模态框初始化
  2. 手动控制Bootstrap Modal实例,先完成局部视图内容加载,再显示模态框,保证逻辑顺序正确
  3. 确认jQuery版本为3.6.0及以上,确保与Bootstrap 5.x兼容

修改后的代码

HTML部分

<a id="btnOpenWidget" class="dropdown-item" 
   href="#" data-bs-target="#divAddCustomWidgetModal" 
   data-backdrop="static" 
   data-url="@Url.Action(Actions._AddWidget, Controllers.Home, new { Area = string.Empty })">
    <span class="glyphicon glyphicon-cog"></span>Open Widget
</a>

<div class="modal fade" id="divAddCustomWidgetModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body"></div>
        </div>
    </div>
</div>

JavaScript部分

$(document).ready(function () {
    $('#btnOpenWidget').click(function (e) {
        // 阻止a标签默认跳转行为
        e.preventDefault();
        var url = $(this).data('url');
        var modalElement = document.getElementById('divAddCustomWidgetModal');
        var modal = new bootstrap.Modal(modalElement);
        
        // 加载局部视图到modal-body,完成后显示模态框
        $('#divAddCustomWidgetModal .modal-body').load(url, function(response, status, xhr) {
            if(status === "success"){
                modal.show();
            } else {
                console.error('局部视图加载失败:', xhr.statusText);
            }
        });
    });
});

额外提示

  • 若局部视图包含Bootstrap组件(如表单、按钮),需确保局部视图内的脚本不会与主页面脚本冲突
  • 给模态框添加modal-dialog和modal-content容器,是Bootstrap 5的标准模态框结构,能避免样式或功能异常

内容的提问来源于stack exchange,提问作者Usama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 15:07:40