ASP.NET Core MVC Beginner

Passing data to views: models, ViewData and ViewBag

Controllers hand data to views in a few ways: a strongly typed model, ViewData, ViewBag and TempData. This lesson shows each one, why the model should carry almost everything, and where the other three still fit.

From controller to view
  1. StartAction loads dataFrom the database or a service
  2. Step 2View(model)Main data, strongly typed
  3. Step 3ViewData["Title"]Small extras for this request
  4. Step 4TempDataMessages that survive a redirect
  5. EndRazor view@model gives typed access to everything

The strongly typed model

Pass one object to View(model) and declare its type at the top of the view with @model. You get IntelliSense, compile-time checks and tag helpers that know the property names.

C#
// Controller
public async Task<IActionResult> Details(int id)
{
    var product = await db.Products.FindAsync(id);
    if (product is null) return NotFound();
    return View(product);
}

In the view

Razor
@model Product

<h1>@Model.Name</h1>
<p>Price: @Model.Price.ToString("C")</p>

@* ViewData for small extras, such as the page title used by the layout *@
@{
    ViewData["Title"] = Model.Name;
}

@if (TempData["Message"] is string message)
{
    <div class="alert">@message</div>
}

ViewData, ViewBag and TempData

  • ViewData is a dictionary of string keys: ViewData["Title"] = "Products". Values are object, so you cast when reading.
  • ViewBag is the same dictionary with dynamic syntax: ViewBag.Title. No compile-time checks; typos fail silently.
  • Both last only for the current request. They suit small extras such as the page title or a dropdown list.
  • TempData survives one redirect (stored in a cookie by default) and is removed once read. Use it for "Saved!" messages after Post/Redirect/Get.

Rule of thumb

If a view needs more than one or two loose values, create a view model class that holds everything it needs and pass that. The view stays typed, tests can check the model, and nothing depends on magic strings. The next lesson covers view models in detail.

Interview question

What is the difference between ViewData, ViewBag and TempData?

ViewData is a string-keyed dictionary and ViewBag is a dynamic wrapper over the same data; both live only for the current request and are untyped. TempData keeps values until they are read in a later request, by default in a cookie, so it survives a redirect. A strongly typed model is preferred for the main data of a view.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.