Please tell meWhat is similarities and differentiate between ViewData and ViewBag with example.
What is similarities and differentiate between ViewData and ViewBag?
34527-Jan-2020
Updated on 27-Jan-2020
Home / DeveloperSection / Forums / What is similarities and differentiate between ViewData and ViewBag?
Please tell meWhat is similarities and differentiate between ViewData and ViewBag with example.
Nishi Tiwari
27-Jan-2020ASP.NET MVC offers us mainly three options - ViewData, ViewBag and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost same but TempData performs additional responsibility.
Similarities between ViewBag & ViewData:
1. Helps to maintain data when we move from controller to view.
2. Both used as to pass data from controller to corresponding view.
3. Both has short life means value becomes null when redirection occurs. That is because their goal is to only provide a way to communicate between controllers and views. It is a communication mechanism for the server call.
Difference between ViewBag & ViewData:
1. ViewData is the dictionary of objects which is derived from ViewDataDictionary class and is accessible using strings as keys.
2. ViewBag is a dynamic property which takes advantage of the new dynamic features in C# 4.0.
3. ViewData also requires typecasting for complex data type and check for null values to avoid error.
4. ViewBag doesn’t require any typecasting for complex data type.
ViewBag & ViewData Example:
ViewBag:-
ViewData:-
In View: