← Back to ASP.NET Core Tutorial Home

Lesson 10: Passing Data with ViewBag, ViewData, and TempData

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

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

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

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"]

Main differences

Rule of thumb: Use models for important structured data. Use ViewBag or ViewData for small extra values. Use TempData for one-time messages across redirects.

Conclusion

ViewBag, ViewData, and TempData are useful tools, but they should not replace strongly typed models when your application needs structured or complex data.

← Previous Lesson Next Lesson: Razor Syntax Basics →