萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 頁面重新整理與跳轉技巧大全

伺服器端導向/重新整理

方法程式碼特點
Response.Redirect`Response.Redirect(Request.Url.ToString())`HTTP 302,瀏覽器重新請求,URL 更新
Response.AddHeader`Response.AddHeader("Refresh", "0")`HTTP Refresh 標頭,0 秒立即重整
Server.Transfer`Server.Transfer("target.aspx")`伺服器端轉移,**URL 不變**,保留 Form/QueryString
Server.Execute`Server.Execute("fragment.aspx")`執行片段並返回,**不改變 URL**

客戶端 JavaScript 重新整理/跳轉

<!-- 1. 立即重整本頁 -->
<script>window.location.reload();</script>

<!-- 2. 重整並清除表單重送提示 (POST→GET) -->
<script>window.location.href = window.location.href;</script>

<!-- 3. 跳轉指定頁面 -->
<script>window.location.href = 'target.aspx';</script>

<!-- 4. 延遲跳轉 -->
<script>setTimeout(() => window.location.href='target.aspx', 3000);</script>

<!-- 5. 重新整理父視窗/框架 -->
<script>window.parent.location.reload();</script>
<script>window.parent.frames['leftFrame'].location.reload();</script>

<!-- 6. 開啟新視窗 -->
<script>window.open('target.aspx', '_blank');</script>

ASP.NET 後端註冊 Script 範例

// 提示後跳轉
ClientScript.RegisterStartupScript(GetType(), "redirect", 
    "alert('儲存成功!'); window.location.href='List.aspx';", true);

// 重新整理父頁面 (適用 ModalDialog/Iframe)
ClientScript.RegisterStartupScript(GetType(), "refreshParent",
    "window.parent.location.reload();", true);

// UpdatePanel 部分更新後重整
ScriptManager.RegisterStartupScript(this, GetType(), "reload", "window.location.reload();", true);

HTML Meta 標籤自動重新整理/跳轉

<head>
  <meta http-equiv="refresh" content="10" /> <!-- 10 秒重整本頁 -->
  <meta http-equiv="refresh" content="5; url=https://example.com" /> <!-- 5 秒跳轉 -->
</head>

常見情境解決方案

情境建議做法
表單送出成功,顯示訊息後回列表`ClientScript.RegisterStartupScript` + `alert` + `window.location.href`
Iframe 內送出,重新整理父頁面`window.parent.location.reload()` 或 `window.parent.frames[0].location.href=...`
Modal 對話框關閉後重新整理開啟者`window.opener.location.reload(); window.close();`
AJAX 部分更新後需全頁重整`ScriptManager.RegisterStartupScript` + `window.location.reload()`
防止重新整理重複提交 (PRG 模式)POST 完成後 `Response.Redirect` 到 GET 頁面

避坑指南

  • `Response.Redirect` 後面的代碼**仍會繼續執行**,建議加 `Response.End()` 或 `return`。
  • `Server.Transfer` 目標頁面無法取得原頁面的 `ViewState` (除非 `preserveForm=true`)。
  • UpdatePanel 內無法使用 `Response.Redirect`/`Server.Transfer`,必須用 `ScriptManager.RegisterStartupScript` 產生客戶端導向。
  • 跨域 Iframe 受同源策略限制,無法 `parent.location.reload()`,需改用 `postMessage` 通訊。
copyright © 萬盛學電腦網 all rights reserved