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