skip to content

In ASP.NET Core MVC views, when do you pass data with @model versus ViewData or ViewBag, and how do they relate?

level: juniorimportance: should knowfreq 62%

answer

  1. View(model) sets ViewData.Model
  2. @model gives a typed Model property
  3. ViewData: string-keyed ViewDataDictionary
  4. ViewBag is dynamic over the same ViewData
  5. [ViewData] on a controller property

basics

~20 s

Pass the page's main data as a typed model with View(model) and @model, which the compiler checks. Use ViewData or ViewBag only for small extras such as the page title; ViewBag is a dynamic wrapper over the same ViewData dictionary.

solid answer

~40 s

`View(model)` stores the object in `ViewData.Model`. A view that declares `@model ListingDetailsViewModel` compiles to a `RazorPage<ListingDetailsViewModel>`, so `Model` is typed, IntelliSense and the compiler check member names, and tag helpers like `asp-for` can bind to it. `ViewData` is a `ViewDataDictionary` of string keys to objects, handy for values that are not part of the model, such as `ViewData["Title"]`, which the layout reads. `ViewBag` is a `dynamic` wrapper over that same dictionary, so `ViewBag.Title` and `ViewData["Title"]` are one entry, and typos fail only at runtime. A property marked `[ViewData]` on a controller is copied into `ViewData` under its name. If the model's type doesn't match `@model`, MVC throws `InvalidOperationException` saying the model item passed is of the wrong type. Keep the main data in the model and use the dictionary sparingly.

code

csharp · 15 lines
csharp
public class ListingsController(IListingStore store) : Controller
{
    [ViewData]
    public string? Title { get; set; }

    public async Task<IActionResult> Details(int id, CancellationToken ct)
    {
        var vm = await store.GetDetailsAsync(id, ct);
        if (vm is null) return NotFound();

        Title = vm.Address;                    // -> ViewData["Title"]
        ViewData["Canonical"] = Url.Action("Details", new { id });
        return View(vm);                       // -> ViewData.Model
    }
}

go deeper

for a junior

Recall that View(model) plus @model gives a typed Model, and that ViewData and ViewBag carry small extras like the page title.

for a middle

Explain that ViewBag wraps the same ViewDataDictionary, how [ViewData] properties work, and how values flow to layouts and to copied partial ViewData.

for a senior

Enforce view models per page, keep dictionary keys few and named, and recognise runtime-only failures from type mismatches and ViewBag typos.

for a principal

Set a convention that pages depend on explicit view models so views stay reviewable and refactor-safe across a large team.

## Three doors into one object Every MVC view receives a **`ViewDataDictionary`**. The model, `ViewData` entries and `ViewBag` properties all live in it: - **`ViewData.Model`** holds the object passed to `View(model)`. - **`ViewData["key"]`** reads and writes string-keyed entries in the same dictionary. - **`ViewBag`** is a `DynamicViewData` object whose properties map to those entries, so `ViewBag.Title = "Lake houses"` and `ViewData["Title"]` are the same value. The controller (`Controller.ViewData`, `Controller.ViewBag`) and the view (`@ViewData`, `@ViewBag`, `@Model`) see the same dictionary for one request, and the layout rendered around the view sees it too. ## @model: the typed path ```razor @model ListingDetailsViewModel <h1>@Model.Address</h1> <p>@Model.Bedrooms bedrooms, @Model.Price.ToString("C0")</p> ``` `@model T` makes the generated class derive from `RazorPage<T>`, so `Model` is a `T`: - member names are checked at **compile time** (views are compiled at build time by the Razor SDK); - refactoring tools rename properties in views too; - tag helpers and HTML helpers such as `asp-for="Price"` work from expressions on `Model`. If the controller passes a different type, rendering fails with `InvalidOperationException`: "The model item passed into the ViewDataDictionary is of type 'ListingSummary', but this ViewDataDictionary instance requires a model item of type 'ListingDetailsViewModel'." ## ViewData and ViewBag: the untyped extras | | `ViewData` | `ViewBag` | |---|---|---| | Type | `ViewDataDictionary` | `dynamic` | | Syntax | `ViewData["Title"]` | `ViewBag.Title` | | Storage | the dictionary itself | the same dictionary | | Typo detection | runtime (null) | runtime (null) | | Needs a cast to use as a type | yes | no, but resolved dynamically | Good uses are small, cross-cutting values the layout needs: the page title, a canonical URL, a flag that hides the search bar. The `mvc` template's views set `ViewData["Title"]` and its `_Layout.cshtml` reads it in `<title>`. From the controller you can also mark a property with **`[ViewData]`**: its value is stored in `ViewData` under the property's name, so `[ViewData] public string Title { get; set; }` feeds `ViewData["Title"]` without string keys in the action. ## How it flows to layouts and partials - The view runs **before** its layout, so a value the view sets in `ViewData` is visible to the layout. That is why the title is set in the view, not the layout. - A partial rendered with `Html.PartialAsync` receives a **copy** of the parent's `ViewData` with its own model. Entries the partial adds do not flow back to the parent. ## Building the view model A listing details page needs the address, price, photos, the agent's contact card and a flag for whether the visitor saved the listing. Rather than passing the EF Core entity and stuffing the rest into `ViewBag`, the action projects into a `ListingDetailsViewModel` that holds exactly what the page renders. This keeps lazy-loading and over-posting concerns out of the view, makes the view's dependencies visible in one type, and lets a unit test assert on the model the action produced (`ViewResult.Model`) without rendering HTML. Layout-level values stay in `ViewData`, ideally behind constants such as `ViewKeys.Title` so a typo becomes a compile error rather than an empty `<title>`. ## What is not part of this - **TempData** survives a redirect by using cookies or session storage; `ViewData` lives only for the current request. They solve different problems. - In a Razor Pages `PageModel`, the page model's own properties are usually the model; `ViewData` exists there too, but `ViewBag` is available only in the `.cshtml`. ## ViewData in unit tests A controller test can read `ViewResult.ViewData["Title"]` or the `[ViewData]` property after calling the action, and `ViewResult.Model` for the typed model, so both channels are testable without rendering. What a test cannot catch is a typo between the key the controller writes and the key the view reads; that gap is another argument for keeping the main data in the model. ## Choosing in practice 1. Build a **view model** per page (`ListingDetailsViewModel`) holding everything the page renders, and pass it with `View(model)`. 2. Use `ViewData` for a handful of layout-level values, ideally behind constants or `[ViewData]` properties. 3. Avoid `ViewBag` in new code: it adds `dynamic` dispatch and hides typos, for no capability `ViewData` lacks. 4. Never put the main data of a page in `ViewBag`; reviewers cannot see what the view depends on, and the compiler cannot help.

  • What happens if the controller passes a ListingSummary to a view declared with @model ListingDetailsViewModel?
    Rendering throws `InvalidOperationException`: the model item passed into the `ViewDataDictionary` is of type `ListingSummary`, but the dictionary requires `ListingDetailsViewModel`. It is a runtime error, because the controller and the view are bound only by the view name.
  • If a partial view sets ViewData["Badge"], can the parent view read it afterwards?
    No. A partial rendered through `Html.PartialAsync` gets a new `ViewDataDictionary` copied from the parent's, so its additions stay in the copy. Pass data down through the partial's model or `ViewData`, never up.

  • ViewBag and ViewData are separate stores, so a value set in one is missing from the other.
  • ViewData survives a redirect to the next request.
  • With @model, a wrong model type is a compile-time error in the controller.
  • ViewBag is faster than ViewData because it avoids dictionary lookups.
  • A layout cannot see ViewData values that the view sets.