Difference between ViewBag and ViewData

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

ViewData, derived from ViewDataDictionary class, is a dictionary object that can be accessed using a string key. Its value becomes null if redirection occurs.

  • 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

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.

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

If you enjoyed this post, let me know by leaving a comment below.


Leave a Reply

Your email address will not be published.Required fields are marked *