ViewBag, ViewData And TempData In MVC

Introduction

ViewBag, ViewData, and TempData are all objects in ASP.NET MVC, and these are used to pass the data in various scenarios.

The following are the scenarios where we can use these objects.

  1. Pass the data from Controller to View.
  2. Pass the data from one action to another action in the same Controller.
  3. Pass the data in between Controllers.
  4. Pass the data between consecutive requests.

What is ViewBag?

ViewBag is a dynamic object to passes the data from the Controller to View. This will pass the data as a property of the object ViewBag. And we have no need to typecast to read the data or for null checking. The scope of ViewBag is permitted to the current request, and the value of ViewBag will become null while redirecting.

Example Controller

Public ActionResult Index()  
{  
    ViewBag.Title = “Welcome”;  
    return View();  
}  

Example View

<h2>@ViewBag.Title</h2>  

What is ViewData?

ViewData is a dictionary object to pass the data from Controller to View, where data is passed in the form of a key-value pair. Typecasting is required to read the data in View if the data is complex, and we need to ensure a null check to avoid null exceptions. The scope of ViewData is similar to ViewBag, and it is restricted to the current request, and the value of ViewData will become null while redirecting.

Example Controller

Public ActionResult Index()  
{  
    ViewData[”Title”] = “Welcome”;  
    return View();  
}  

Example View

<h2>@ViewData[“Title”]</h2>  

What is TempData?

TempData is a dictionary object to passes the data from one action to another action in the same Controller or different Controllers. Usually, the TempData object will be stored in a session object. Tempdata is also required to typecast and for null checking before reading data from it. TempData scope is limited to the next request, and if we want TempData to be available even further, we should use Keep and Peek.

Example Controller

Public ActionResult Index()  
{  
    TempData[”Data”] = “I am from Index action”;  
    return View();  
}  

Public string Get()  
{  
    return TempData[”Data”] ;  
}  

To summarize, ViewBag and ViewData are used to pass the data from a Controller action to View, and TempData is used to pass the data from action to another action or one Controller to another Controller. 

Hope you have understood the concepts of ViewBag, ViewData, and TempData. Thanks for reading!

Next Recommended Reading ViewData VS ViewBag Vs TempData in MVC