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

ASP.NET中Bootstrap 5 Modal无法显示问题求助

Bootstrap 5模态框无法触发的修复方案

问题现象

点击模态框触发按钮无响应,控制台抛出Uncaught TypeError: Cannot read properties of undefined (reading 'Modal')错误,使用Bootstrap 5.0.2版本,按官方规范无需自定义JS即可实现模态框基础交互,但当前功能失效。

问题根源

代码中使用了Bootstrap 4的旧版数据属性,而Bootstrap 5对所有交互类数据属性添加了统一的bs-前缀,导致框架无法识别触发指令:

  • 触发按钮使用了旧属性data-target,而非Bootstrap 5要求的data-bs-target
  • 关闭按钮使用了旧属性data-dismiss,而非Bootstrap 5要求的data-bs-dismiss
  • 模态框的无障碍属性aria-labelledby未正确关联标题ID(可选优化项)

修复后的代码(Index.cshtml)

<button class="rectangle-button-lg button-grey" data-bs-toggle="modal" data-bs-target="#normalModal">Normal</button>
<div class="modal fade" id="normalModal" tabindex="-1" aria-labelledby="normalModalTitle" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header ref-modal-header">
                <button type="button" class="close" data-bs-dismiss="modal">
                    &times;
                </button>
                <h4 class="modal-title ref-modal-title" id="normalModalTitle">
                    Please Read!
                </h4>
            </div>
            <div class="modal-body ref-modal-body">
                <p>Before you start please ensure to follow the instructions</p>
            </div>
        </div>
    </div>
</div>

补充说明

你的_Layout.cshtml中已正确引入Bootstrap 5的CSS和包含Popper.js的bundle JS,依赖配置无问题,仅需修正数据属性前缀即可恢复功能。另外修复了模态框标题的ID关联,优化了无障碍访问性。

内容的提问来源于stack exchange,提问作者A.Mac

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 06:45:22