Explain the differences between View Bag, View Data & Temp Data?

ViewData, ViewBag & TempData all these are state management techniques in ASP.NET MVC.

ViewData and ViewBag

ViewData & ViewBag are quite similar. Both are used to transfer information from the controller's action to view. But below are some key differences between them.

  1. ViewData uses the dictionary to store the data while ViewBag is a dynamic object.
  2. Type Casting is required to retrieve the data from ViewData while in case of ViewBag, there is no need of TypeCasting.
  3. ViewData is faster as it uses Dictionary in the background.

Syntax for ViewData:

ViewData["Email"] = "ankushjain358@gmail.com";

Syntax for ViewBag:

ViewBag.Email = "ankushjain358@gmail.com";

TempData

TempData is a bit different, this is used to transfer information from one controller action to another controller action during full page redirects. TempData uses session behind the scenes.

Syntax for TempData:

TempData["Email"] = "ankushjain358@gmail.com";

ViewData & ViewBag both are the properties of ControllerBase class. Type of ViewData is ViewDataDictionary while type of ViewBag is dynamic. Visit ControllerBase class here.

Interview Questions by Technologies
This site uses cookies. By continuing to browse the site you are agreeing to our use of cookies. For more information - please visit our private policy.