Difference Between ViewData and TempData?
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 the TempData
lifecycle.
As Ben Scheirman said here:
TempData is a session-backed temporary storage dictionary that is available for one single request. It’s great to pass messages between controllers.
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.
ViewData:
-
ViewData
is a dictionary typepublic ViewDataDictionary ViewData { get; set; }
- It can be used to pass data from controller to view, one way only
- It’s life lies only during the current request
- If passing string then no need to typecast
- If passing object then you need to typecast it but before that you need to check if it is not null
- Its a property on
ControllerBase
, which is the parent ofController
class
TempData:
-
TempData
internally useTempDataDictionary
:public TempDataDictionary TempData { get; set; }
- Once data is saved into
TempDataDictionary
object:- It persists in it and can be read from any view or any action in any controller
- It can only be read once; once read, it becomes null
- It is saved into session so on expiration of session data is lost.
This behavior is new from ASP.NET MVC 2 and latter versions.
In earlier versions of ASP.NET MVC, the values in TempData
were available only until the next request.
- It’s alive, until it is read or session expires and can be read from anywhere.
See the comparison of ViewData, ViewBag, TempData and Session in MVC in detail
I found this comparison useful: http://www.dotnet-tricks.com/Tutorial/mvc/9KHW190712-ViewData-vs-ViewBag-vs-TempData-vs-Session.html
One gotcha I came across is that TempData values are cleared after they are read by default. There are options, see methods 'Peek' and 'Keep' on Msdn for more info.