views:

283

answers:

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

+5  A: 

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.

Malcolm Frexner
Interesting, never heard of it. :-)
Thomas Stock
it's a bummer tho that you have to use "TempData" in the view too, and can't just keep using ViewData there. But it works nicely, so thanks.
Thomas Stock
See the copy extension method http://blog.eworldui.net/post/2008/06/MVC-Post-Redirect-Get-Sample-Updated.aspx
James S
+1  A: 

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

eu-ge-ne
+1 for PRG pattern
Thomas Stock
A: 

If you need this more than once, a nice workaround would be creating ActionFilterAttributes which export/import the tempdata to viewdata and vice-versa. You can pass your ModelState in this way very nicely as well (demonstrated here - #13). With a few adjustments to that piece of code you would have a clean solution, I think.

Leon