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?
ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks. TempData is also a dictionary object that stays for the time of an HTTP Request.
ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. ViewData requires typecasting for complex data type and check for null values to avoid error.
ViewData and ViewBag are used for the same purpose -- to transfer data from controller to view. ViewData is nothing but a dictionary of objects and it is accessible by string as key. ViewData is a property of controller that exposes an instance of the ViewDataDictionary class.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With