在 ASP.NET MVC 中基本上有 3 种技术来实现PRG pattern。
使用TempData 确实是为单个重定向传递信息的一种方式。我看到这种方法的缺点是,如果用户在最终重定向页面上按 F5,他将不再能够获取数据,因为后续请求将从 TempData 中删除数据:
[HttpPost]
public ActionResult SubmitStudent(StudentResponseViewModel model)
{
if (!ModelState.IsValid)
{
// The user did some mistakes when filling the form => redisplay it
return View(model);
}
// TODO: the model is valid => do some processing on it
TempData["model"] = model;
return RedirectToAction("DisplayStudent");
}
[HttpGet]
public ActionResult DisplayStudent()
{
var model = TempData["model"] as StudentResponseViewModel;
return View(model);
}
如果您没有很多数据要发送,另一种方法是将它们作为查询字符串参数发送,如下所示:
[HttpPost]
public ActionResult SubmitStudent(StudentResponseViewModel model)
{
if (!ModelState.IsValid)
{
// The user did some mistakes when filling the form => redisplay it
return View(model);
}
// TODO: the model is valid => do some processing on it
// redirect by passing the properties of the model as query string parameters
return RedirectToAction("DisplayStudent", new
{
Id = model.Id,
Name = model.Name
});
}
[HttpGet]
public ActionResult DisplayStudent(StudentResponseViewModel model)
{
return View(model);
}
另一种方法,恕我直言,最好的方法是将这个模型持久化到某个数据存储中(比如数据库或其他东西,然后当你想重定向到 GET 操作时,只发送一个 id 允许它从你的任何地方获取模型坚持下去)。这是模式:
[HttpPost]
public ActionResult SubmitStudent(StudentResponseViewModel model)
{
if (!ModelState.IsValid)
{
// The user did some mistakes when filling the form => redisplay it
return View(model);
}
// TODO: the model is valid => do some processing on it
// persist the model
int id = PersistTheModel(model);
// redirect by passing the properties of the model as query string parameters
return RedirectToAction("DisplayStudent", new { Id = id });
}
[HttpGet]
public ActionResult DisplayStudent(int id)
{
StudentResponseViewModel model = FetchTheModelFromSomewhere(id);
return View(model);
}
每种方法都有其优点和缺点。由您来选择最适合您的场景。