
使用者送出表單(POST),伺服器直接回傳 HTML(200 OK)。此時重新整理會再次送出 POST,導致重複下單、重複扣款等嚴重後果。
Post / Redirect / Get:
Location 標頭)。Location 指定的 URL。
Response.Redirect 並處理 ViewState/控制項狀態,極繁瑣。return RedirectToAction(...) 一行搞定。public class AccountController : Controller {
// GET: 顯示登入頁
public ActionResult Login() {
return View();
}
// POST: 處理登入提交
[HttpPost]
public ActionResult Login(LoginViewModel model, string returnUrl) {
if (!ModelState.IsValid) return View(model);
if (Membership.ValidateUser(model.UserName, model.Password)) {
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
// PRG 關鍵:重導向而非直接回傳 View
return RedirectToAction("Index", "Home"); // 或 return Redirect(returnUrl);
}
ModelState.AddModelError("", "帳號或密碼錯誤");
return View(model); // 驗證失敗留在原頁(POST → View 例外情況)
}
}
[HttpPost]
public ActionResult Create(Product product) {
if (ModelState.IsValid) {
_repo.Add(product);
TempData["SuccessMessage"] = "產品已新增"; // 只存活一個請求
return RedirectToAction("Index"); // PRG
}
return View(product);
}
// Index.cshtml
@if (TempData["SuccessMessage"] != null) {
@TempData["SuccessMessage"]
}
RedirectToAction/Redirect。TempData 跨請求傳遞一次性訊息(成功/錯誤)。View(model) 保留輸入與錯誤訊息(POST → View 為唯一例外)。徹底落實 PRG,即可消除重複提交、瀏覽器警告、書籤失效等經典 Web 應用痛點,是 MVC 開發者的必修內功。