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