首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 在 iframe 中彈出訊息並跳轉頁面的實作技巧

     編輯:ASP.NET 基礎

應用場景

在使用 <iframe> 架構的後台管理系統中,子頁面完成儲存操作後,需彈出提示訊息並導向父視窗的指定功能頁(如列表頁)。傳統 Response.Redirect 僅能導向 iframe 內部,無法控制父框架導航,需透過 JavaScript 操作 window.parent 達成。

通用輔助方法

public static class MessageBox
{
    /// <summary>
    /// 在 iframe 中彈出警示並導向父視窗指定頁面
    /// </summary>
    public static void ResponseShowMsg(string msg, string targetPageName)
    {
        // 取得目前完整 URL
        string currentUrl = HttpContext.Current.Request.Url.OriginalString;
        string baseUrl;

        if (currentUrl.LastIndexOf('?') > 0)
        {
            // 移除查詢字串與目前頁面檔名,替換為目標頁面
            baseUrl = currentUrl.Substring(0, currentUrl.LastIndexOf('?'))
                .Replace(HttpContext.Current.Request.Url.Segments[HttpContext.Current.Request.Url.Segments.Length - 1], targetPageName);
        }
        else
        {
            baseUrl = currentUrl.Replace(HttpContext.Current.Request.Url.Segments[HttpContext.Current.Request.Url.Segments.Length - 1], targetPageName);
        }

        string script = $@"
<script>
    alert('{msg}');
    window.parent.frames['sysMain'].location.href = '{baseUrl}';
</script>";

        HttpContext.Current.Response.Write(script);
    }
}

前端頁面呼叫範例

protected void btnSave_Click(object sender, EventArgs e)
{
    if (bll.RoleAdd(model, tempMs))
    {
        MessageBox.ResponseShowMsg("儲存成功!", "add.aspx");
    }
    else
    {
        MessageBox.Show(this, "儲存失敗!"); // 僅彈窗不跳轉
    }
}

關鍵點解析

  • 動態組合目標 URL:透過 Request.Url.Segments 取得目前頁面檔名並替換,避免硬編碼路徑,支援多層目錄結構。
  • 指定父框架目標:window.parent.frames['sysMain'] 需與主框架頁面的 iframe name 屬性一致。
  • 編碼安全:實務上建議對 msg 進行 JavaScript 字串逸出(如 HttpUtility.JavaScriptStringEncode),防止 XSS 或語法錯誤。

現代化替代方案

若專案允許,建議改用 AJAX + 前端路由 或 SignalR 推播通知,避免內嵌 <script> 回應造成的維護困擾與安全風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved