In ASP.NET MVC, ViewData, ViewBag, and TempData are used to pass data between controllers and views, but they each have their unique characteristics.
ViewData
public ActionResult Index()
{
ViewData["Message"] = "Hello from ViewData!";
return View();
}
//View
<p>@ViewData["Message"]</p>
ViewBag
public ActionResult Index()
{
ViewBag.Message = "Hello from ViewBag!";
return View();
}
//View
<p>@ViewBag.Message</p>
TempData
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 |