In ASP .NET MVC, ViewBag and ViewData are used to pass data from controller to view. Both the items are available only for the current request and are similar in behavior. Now the question is, what is the difference between ViewBag and ViewData?
ViewData, derived from ViewDataDictionary class, is a dictionary object that can be accessed using a string key. Its value becomes null if redirection occurs.
//Setting Data ViewData["message"]="Hi from controller"; //Accessing Data <h1>@ViewData["message"]</h1>
- It is just a dictionary with key-value pairs.
- It has a string as the key.
- ViewData requires complex datatypes should be typecasted.
- Null values should be checked to avoid errors.
ViewBag was introduced in .NET 4.0. It is also used to pass data from controller to view. Like ViewData, its data is available only for the current request and is set to null if redirection occurs.
//Setting Data ViewBag.Message="Hi from controller"; //Accessing Data <h1>@ViewData.Message</h1>
- It is a dynamic wrapper around ViewData.
- ViewBag internally uses the same ViewData dictionary to store data.
- It does not require data to be typecasted.
Join the newsletter to get the latest updates.