keep viewdata on RedirectToAction

Thomas Stock picture Thomas Stock · Aug 4, 2009 · Viewed 23.6k times · Source
[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.

Answer

Mathias F picture Mathias F · Aug 4, 2009

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.