MVC-ViewData vs ViewBag vs TempData


In ASP.NET MVC, ViewData, ViewBag, and TempData are used to pass data between controllers and views, but they each have their unique characteristics.

MVC ViewData vs ViewBag vs TempData

ViewData

  1. It's a dictionary object that is derived from ViewDataDictionary.
  2. Data is accessed using string keys.
  3. It's useful for passing data from the controller to the view.
  4. Data is available only during the current request.
public ActionResult Index()
{
    ViewData["Message"] = "Hello from ViewData!";
    return View();
}

//View

<p>@ViewData["Message"]</p>

ViewBag

  1. It's a dynamic object that uses the ExpandoObject under the hood.
  2. Easier syntax compared to ViewData as it doesn't require casting.
  3. Also used for passing data from the controller to the view.
  4. Data is available only during the current request.
public ActionResult Index()
{
    ViewBag.Message = "Hello from ViewBag!";
    return View();
}

//View
<p>@ViewBag.Message</p>

TempData

  1. It's a dictionary object derived from TempDataDictionary.
  2. Stores data that is needed for more than a single request, useful for redirection.
  3. Data persists until it is read, or the session expires.
  4. Data is accessed using string keys.
public ActionResult Index()
{
    TempData["Message"] = "Hello from TempData!";
    return RedirectToAction("NextAction");
}

public ActionResult NextAction()
{
    string message = TempData["Message"] as string;
    ViewBag.Message = message;
    return View();
}

//View

<p>@ViewBag.Message</p>

Here's a comparison of ViewData, ViewBag, and TempData in tabular form.

Feature ViewData ViewBag TempData
Type Dictionary (ViewDataDictionary) Dynamic (ExpandoObject) Dictionary (TempDataDictionary)
Syntax ViewData["Key"] ViewBag.Key TempData["Key"]
Casting Requires casting No casting required Requires casting
Scope Current request Current request Subsequent requests (short-lived)
Usage Pass data from controller to view Pass data from controller to view Pass data between controller actions
Persistence Data is lost after the request is complete Data is lost after the request is complete Data persists until read or session expires

Next