articles

Home / DeveloperSection / Articles / Difference between ViewData, ViewBag and TempData

Difference between ViewData, ViewBag and TempData

Hemant Patel5679 08-Sep-2017

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.
Difference between ViewData, ViewBag and TempData
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.
Difference between ViewData, ViewBag and TempData
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. 

Updated 28-Mar-2020
Exploring the online world is my passion. have experience of #content writing #SEO #Digital Marketing #On-Page #Lead Generation #Content Analyst #Marketing Analyst... I could never stop at one point, continuously wanted to acquire more and more skills. My work for any organization will be full of passion and hard work.

Leave Comment

Comments

Liked By