views:

3317

answers:

2

I know what ViewData is and use it all the time, but in ASP.NET Preview 5 they introduced something new called TempData.

I normally strongly type my ViewData, instead of using the dictionary of objects approach.

So, when should I use TempData instead of ViewData?

Are there any best practices for this?

+29  A: 

In one sentence: TempData are like ViewData with one difference: They only contain data between two successive requests, after that they are destroyed. You can use tempdata to pass error messages or something similar.

Although outdated, this article has good description of TempData lifecycle: http://www.squaredroot.com/post/2007/12/MVC-ViewData-vs-TempData.aspx

As Ben Scheirman said here: http://flux88.com/testingtempdatainaspnetmvc.aspx, "TempData is a session-backed temporary storage dictionary that is available for one single request. It’s great to pass messages between controllers."

HTH
Dragan

Dragan Panjkov
+5  A: 

When an action returns a RedirectToAction result it causes an HTTP redirect (equivalent to Response.Redirect). Data can be preserved in the TempData property (dictionary) of the controller for the duration of a single HTTP redirect request.

Seventh Element