// 重導向至目前頁面 (重新整理)
Response.Redirect(Request.Url.ToString());
// 重導向至指定頁面
Response.Redirect("~/Default.aspx");
特點:HTTP 302 回應、瀏覽器網址列更新、可跨網域、會終止目前要求管線 (後續程式碼不執行)。
// 方式 A: window.location.href
Response.Write("");
// 方式 B: window.location.reload()
Response.Write("");
// 方式 C: 帶提示訊息後導向
Response.Write("");
特點:不中斷伺服器端程式碼執行、可在 UpdatePanel 部分更新中使用、需注意腳本註冊時機。
// 立即重新整理
Response.AddHeader("Refresh", "0");
// 3 秒後導向指定頁面
Response.AddHeader("Refresh", "3;url=Target.aspx");
特點:HTTP 標頭層面控制、不依賴 JavaScript、SEO 友善度較低。
// 轉交給另一頁面處理 (網址列不變)
Server.Transfer("Target.aspx");
// 執行另一頁面並回傳結果
Server.Execute("Target.aspx");
差異:Transfer 完全移交控制權;Execute 回來繼續執行。兩者皆不更新瀏覽器網址。
<meta http-equiv="refresh" content="5;url=Target.aspx" />
<!-- 5 秒後導向 Target.aspx,content="0" 為立即重整 -->
<script>
// 10 秒重整一次
setInterval(function() { window.location.reload(); }, 10000);
// 或倒數計時顯示
var count = 10;
setInterval(function() {
document.title = count + " 秒後重新整理";
if (--count <= 0) window.location.reload();
}, 1000);
</script>
// 父頁面重新整理子框架
parent.frames["leftFrame"].location.reload();
// 子框架重新整理父頁面
parent.location.reload();
// 子框架重新整理同層另一框架
parent.frames["rightFrame"].location.href = "NewPage.aspx";
<script>
// 子視窗關閉前
window.opener.location.reload();
window.close();
</script>
在 UpdatePanel 非同步回傳中,Response.Redirect 與 Response.Write 皆可能失效,需使用 ScriptManager:
// 正確方式
ScriptManager.RegisterStartupScript(this, GetType(), "reload", "window.location.reload();", true);
// 錯誤示範 (非同步回傳無效)
Response.Redirect(Request.Url.ToString());
| 情境 | 推薦方式 | 關鍵點 |
|---|---|---|
| 表單送出成功,導向列表頁 | Response.Redirect("List.aspx") | POST-Redirect-GET 模式,防重複送出 |
| AJAX 回傳後重新整理頁面 | ScriptManager.RegisterStartupScript | 搭配 UpdatePanel 使用 |
| 儲存成功顯示提示再導向 | Response.Write + alert + location.href | 或用 SweetAlert2 等美化彈窗 |
| 定時自動重新整理儀表板 | Meta Refresh 或 JS setInterval | Meta 不需 JS 支援;JS 可控制更精細 |
| 跨框架頁面同步更新 | parent.frames[name].location.href | 同網域限制 |
| 伺服器端邏輯決定轉交頁面 | Server.Transfer | 網址不變、共享 Request/Session |
Response.End() 或 return。Sys.WebForms.PageRequestManagerParserErrorException。