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

ASP.NET服务端代码中如何调用Bootstrap提示框替代原生alert

如何修改服务端代码实现Bootstrap提示框通知

前提准备

首先确保你的ASPX页面已经引入Bootstrap依赖资源(以Bootstrap 4为例):

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
<!-- jQuery(Bootstrap 4依赖) -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.4/dist/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

修改MessageBox类代码

核心是替换page_Unload方法里的原生alert脚本,改为生成Bootstrap模态框的代码,同时处理消息内容的转义以避免JavaScript语法错误:

static MessageBox()
{
    // Create the store
    pageTable = new Dictionary<Page, Queue>();
}

public static void Show(string str)
{
    // Lets find out what page is sending the request
    Page page = HttpContext.Current.Handler as Page;

    // If a valid page is found
    if (page != null)
    {
        // Check if this page is requesting message show for the first time
        if (pageTable.ContainsKey(page) == false)
        {
            // Lets create a message queue dedicated for this page.
            pageTable.Add(page, new Queue());
        }

        // Let us add messages of this to the queue now
        pageTable[page].Enqueue(str);

        // Now let put a hook on the page unload where we will show our message
        page.Unload += new EventHandler(page_Unload);
    }
}

static void page_Unload(object sender, EventArgs e)
{
    // Lets find out which page is getting unloaded
    Page page = sender as Page;

    // If a valid page is found
    if (page != null && pageTable.ContainsKey(page) && pageTable[page].Count > 0)
    {
        string message = pageTable[page].Dequeue().ToString();
        // 转义消息内容,避免JavaScript语法错误
        string escapedMessage = message.Replace("'", "\\'").Replace("\n", "\\n").Replace("\r", "\\r");

        // 输出Bootstrap模态框的HTML和触发脚本
        string bootstrapModalScript = $@"
<script>
// 检查页面是否已存在模态框,避免重复创建
if (!document.getElementById('messageModal')) {{
    // 动态创建模态框HTML
    var modalHTML = `
        <div class='modal fade' id='messageModal' tabindex='-1' role='dialog' aria-labelledby='messageModalLabel' aria-hidden='true'>
            <div class='modal-dialog' role='document'>
                <div class='modal-content'>
                    <div class='modal-header'>
                        <h5 class='modal-title' id='messageModalLabel'>提示</h5>
                        <button type='button' class='close' data-dismiss='modal' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                    </div>
                    <div class='modal-body'>{escapedMessage}</div>
                    <div class='modal-footer'>
                        <button type='button' class='btn btn-primary' data-dismiss='modal'>确定</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', modalHTML);
}}
// 显示模态框
$('#messageModal').modal('show');
</script>";

        HttpContext.Current.Response.Write(bootstrapModalScript);
        // 移除当前页面的队列,避免重复触发
        pageTable.Remove(page);
    }
}

调用方式保持不变

你依然可以用原来的方式调用:

MessageBox.Show("test message");

关键修改点说明

  • 消息转义:对消息中的单引号、换行符进行转义,防止JavaScript字符串语法错误。
  • 动态创建模态框:先检查页面是否已有模态框元素,避免重复创建DOM节点。
  • Bootstrap模态框触发:使用$('#messageModal').modal('show')调用Bootstrap的模态框显示方法。
  • 清理队列:显示消息后移除页面对应的队列,避免后续重复输出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 11:27:26