Besides models, ASP.NET Core also provides several lightweight ways to pass data from a controller to a view. The most common are ViewBag, ViewData, and TempData.
ViewBag is a dynamic object that lets you store and retrieve values without explicit casting.
public IActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET Core";
return View();
}
In the view:
@ViewBag.Message
ViewData is a dictionary-like object. It stores data using keys.
public IActionResult Index()
{
ViewData["Message"] = "Hello from ViewData";
return View();
}
In the view:
@ViewData["Message"]
TempData is used when you want data to persist for the next request. It is often used after redirects, such as showing a success message after saving a record.
public IActionResult Save()
{
TempData["Success"] = "Record saved successfully";
return RedirectToAction("Index");
}
In the next view:
@TempData["Success"]
ViewBag, ViewData, and TempData are useful tools, but they should not replace strongly typed models when your application needs structured or complex data.