ViewData, TempData and ViewBag are a way to pass data from controller to view and also in the next subsequent request, it’s provided by ASP.NET MVC framework. In MVC ViewBag and ViewData are used to communicate controller and its corresponding view. But communication between controller and corresponding view is only for server call, if the redirect occurs it becomes null. In simple word we can say that it’s a procedure to maintain state between controller and corresponding view.

ViewBag is dynamic property, which is newly added in C# 4.0 feature, but ViewData is a dictionary object. ViewData requires typecasting for complex logic and also ViewData is a dictionary object that’s accessible using string as a key. In other word we can say that ViewBag does not have null checks and typecasting. TempData being a dictionary object, which is staying for the time of an HTTP Request. So, It can be used to maintain data between redirects. For Example, from one controller to the other controller.
ViewData and ViewBag both of these options are limited to a single server call. That means meant its value will be null if a redirect occurs. But TempData is used to maintain state from one Controller to another in redirect case. In this case TempData is the other available option.
ViewData requires typecasting as well as null checks As compared to ViewBagTempData is primarily a dictionary object derived from TempDataDictionary. Its remaining for a successive HTTP Request as opposed to ViewBag and ViewData those stay only for ongoing request. So we say that its can be used to maintain data between controller actions as well as redirects. 
  Modified On Nov-30-2017 07:12:15 AM

Leave Comment