Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ViewData, ViewBag and TempData? [duplicate]

I'm using .net mvc 4.0 for my new project. I want to know What is the difference between ViewData, ViewBag and TempData?

I tried searching on net but didn't find any well document material.

like image 320
swati gupta Avatar asked Feb 03 '15 12:02

swati gupta


People also ask

What is the difference between ViewBag ViewData and TempData?

We have three options: ViewData, ViewBag and TeampData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and it helps us to transfer the data from controller to view whereas TempData also works during the current and subsequent requests.

What is the main difference between ViewBag and ViewData?

Difference between ViewBag & 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.

How is TempData different from ViewData?

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.

Which is faster ViewBag or ViewData in MVC?

Requires typecasting for complex data type and checks for null values to avoid error. If redirection occurs, then its value becomes null. ViewData is faster than ViewBag.


1 Answers

From Top 10 ASP.NET MVC Interview Questions,

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e., ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism to maintain state between controller and corresponding view.

ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). 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. So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the other controller.

like image 136
Sumit Chourasia Avatar answered Oct 28 '22 08:10

Sumit Chourasia