ASP.NET MVC has basically 3 methods for implementing a PRG template.
Using TempData indeed one way to transfer information for a single redirect. The drawback that I see with this approach is that if the user presses F5 on the last redirected page, he will no longer be able to retrieve the data, since he will be removed from TempData for subsequent requests:
[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); }
Another approach, if you do not have a large amount of data to send, is to send them as query string parameters, for example:
[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); }
Another approach and IMHO the best thing is to save this model in some kind of data store (for example, in a database or something else, and then when you want to redirect the GET action, send only the identifier that allows it to choose the model from anywhere saved it). Here's the pattern:
[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); }
Each method has its pros and cons. You can choose which one is best for your scenario.
source share