Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep viewdata on RedirectToAction

[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.

like image 985
Thomas Stock Avatar asked Aug 04 '09 08:08

Thomas Stock


People also ask

How do you preserve ModelState errors across RedirectToAction?

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.

When should we use ViewData?

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).

How do I use TempData keep in view?

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.

What is keep in TempData?

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.


2 Answers

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.

like image 55
Mathias F Avatar answered Sep 30 '22 11:09

Mathias F


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).

like image 23
eu-ge-ne Avatar answered Sep 30 '22 09:09

eu-ge-ne