March 12, 2018

Srikaanth

What is ViewData and ViewBag In ASP.NET MVC

ViewData and ViewBag are used for the same purpose to transfer data from controller to view.

ViewData is nothing but a dictionary of objects and it is accessible by string as key.

ViewData is a property of controller that exposes an instance of the ViewDataDictionary class.

ViewBag is very similar to ViewData. ViewBag is a dynamic property (dynamic keyword which is introduced in .net framework 4.0). ViewBag is able to set and get value dynamically and able to add any number of additional fields without converting it to strongly typed. ViewBag is just a wrapper around the ViewData.

In Asp.Net MVC there are three ways to pass/store data between the controllers and views.

What is ViewData?

  • ViewData is used to pass data from controller to view
  • It is derived from ViewDataDictionary class
  • It is available for the current request only
  • Requires typecasting for complex data type and checks for null values to avoid error
  • If redirection occurs, then its value becomes null.

What is ViewBag?

  • ViewBag is also used to pass data from the controller to the respective view
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0
  • It is also available for the current request only
  • If redirection occurs, then its value becomes null
  • Doesn’t require typecasting for complex data type.

What is TempData?

  • TempData is derived from TempDataDictionary class
  • TempData is used to pass data from the current request to the next request
  • It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action
  • It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages.

ViewData, ViewBag and TeampData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and it helps us to transfer the data from controller to view whereas TempData also works during the current and subsequent requests.


Subscribe to get more Posts :