Difference Between ViewBag, ViewData, & TempData

Introduction

In the context of ASP.NET MVC or ASP.NET Core, ViewBag, ViewData, and TempData are mechanisms for passing data between a controller and a view. They have slightly different characteristics and lifetimes, as described below:

ViewBag in ASP.Net Core

The ViewBag is a dynamic property that allows you to pass data from a controller to a view. It uses the dynamic keyword, which means you can assign any type of value to it. The ViewBag data is available only during the current request and is not stored between subsequent requests. It is a simple and convenient way to transfer data between a controller and a view without the need for creating a specific model.

Controller Action For View Bag

public class HomeController: Controller {
  public ActionResult ViewBagAction() {
    ViewBag.Countries = new List < string > () {
      "Pakistan",
      "India",
      "Nepal",
      "United States"
    };
    return View();
  }
}

View 

@{
    ViewBag.Title = "ViewBagAction";
}
<main>
    <h3>Countires </h3>
    @foreach (string countries in ViewBag.Countries)
    {
        <ul>
            <li>@countries</li>
        </ul>
    }
</main>

ViewData in ASP.Net Core

The ViewData is a dictionary-like object that is derived from the ViewDataDictionary class. It is similar to ViewBag but uses a dictionary instead of dynamic properties. ViewData also allows you to pass data from a controller to a view, but the syntax for accessing the data in the view is slightly different.

Controller Action For View Data

public ActionResult ViewDataAction() {
  ViewData["Countries"] = new List < string > () {
    "Pakistan",
    "India",
    "Nepal",
    "United States"
  };
  return View();
}

TempData in ASP.Net Core

The TempData is also a dictionary-like object derived from the TempDataDictionary class. It is used to store data between requests, particularly when you need to pass data from one action method to another within the same or subsequent requests. TempData uses a session-based storage mechanism, but the data stored in TempData is removed after it has been accessed once. TempData is often used in scenarios like after a form submission, where you want to display a message on a redirected page.

public ActionResult ViewBagAction() {
  TempData["Message"] = "Hello, ViewDataAction!";
  ViewBag.Countries = new List < string > () {
    "Pakistan",
    "India",
    "Nepal",
    "United States"
  };
  return RedirectToAction("ViewDataAction");
}

public ActionResult ViewDataAction() {
  string message = TempData["Message"] as string;
  TempData.Keep();
  ViewData["Countries"] = new List < string > () {
    "Pakistan",
    "India",
    "Nepal",
    "United States"
  };
  return View((object) message);
}

View Data Action output

ViewBag and ViewData pass data from a controller to a view during the same request, while TempData passes data between subsequent requests.


Similar Articles