ASP.NET MVC 中基本上有 3 种技术来实现PRG模式 http://en.wikipedia.org/wiki/Post/Redirect/Get.
Using 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);
}
每种方法都有其优点和缺点。您可以选择最适合您场景的一种。