Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between ViewData and TempData?

Tags:

asp.net-mvc

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?

like image 392
Elijah Manor Avatar asked Oct 06 '08 03:10

Elijah Manor


People also ask

What is difference between TempData and ViewBag?

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.

What is the difference between ViewBag and ViewData?

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.

What is the difference between View and ViewData is asp net?

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.

When should we use ViewData?

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


1 Answers

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.

like image 72
Dragan Panjkov Avatar answered Oct 07 '22 10:10

Dragan Panjkov