在使用 <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, "儲存失敗!"); // 僅彈窗不跳轉
}
}
Request.Url.Segments 取得目前頁面檔名並替換,避免硬編碼路徑,支援多層目錄結構。window.parent.frames['sysMain'] 需與主框架頁面的 iframe name 屬性一致。msg 進行 JavaScript 字串逸出(如 HttpUtility.JavaScriptStringEncode),防止 XSS 或語法錯誤。若專案允許,建議改用 AJAX + 前端路由 或 SignalR 推播通知,避免內嵌 <script> 回應造成的維護困擾與安全風險。