[AcceptVerbs(HttpVerbs.Post)] public ActionResult CreateUser([Bind(Exclude = "Id")] User user) { ... db.SubmitChanges(); ViewData["info"] = "The account has been created."; return RedirectToAction("Index", "Admin"); }
This doesnt keep the "info" text in the viewdata after the redirectToAction. How would I get around this issue in the most elegant way?
My current idea is to put the stuff from the Index controlleraction in a [NonAction] and call that method from both the Index action and in the CreateUser action, but I have a feeling there must be a better way.
Thanks.
Basically, use TempData to save and restore the ModelState object. However, it's a lot cleaner if you abstract this away into attributes. E.g. If you also want to pass the model along in TempData (as bigb suggested) then you can still do that too.
All three objects are available as properties of both the view and controller. As a rule of thumb, you'll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views).
You can use Keep() when prevent/hold the value depends on additional logic. when you read TempData one's and want to hold for another request then use keep method, so TempData can available for next request as above example.
The Keep function is used to preserve the data of TempData object even after the value is read while the Peek function is used to read the value without clearing it. TempData Default functioning. When value is read from the TempData object, the value is cleared and NULL value is assigned.
You can use TempData
.
TempData["info"] = "The account has been created."
.
TempData exists exactly for this situation. It uses Session as storage, but it will not be around after the second response.
From MSDN:
A typical use for a TempDataDictionary object is to pass data from an action method when it redirects to another action method. For example, an action method might store information about an error in the controller's TempData property (which returns a TempDataDictionary object) before it calls the RedirectToAction method. The next action method can then handle the error and render a view that displays an error message.
Use ViewData
if your data should be accessible in View
during "this" request. Use `TempData' if your data is for "next" request (for example POST-REDIRECT-GET design pattern).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With