In this lesson, you will learn how to bridge the gap between your server-side controllers and your HTML views using ViewData and ViewBag.
When your controller performs logic—like fetching a user profile or calculating a summary—you often need to pass that specific result to your Razor view to display it. ASP.NET Core provides two "dictionary-like" objects specifically for this purpose.
Using ViewData
ViewData is a dictionary that stores data using string-based keys. Because it stores values as object types, you must explicitly cast them back to their original type when accessing them in your view.
In the Controller:
ViewData["Title"] = "User Dashboard";
ViewData["Message"] = "Welcome back, developer!";
In the View:
<h1>@ViewData["Title"]</h1>
<p>@(ViewData["Message"] as string)</p>
Using ViewBag
ViewBag is a wrapper around ViewData that uses C# dynamic properties. It offers a cleaner syntax because it eliminates the need for manual casting, making your code feel more readable.
In the Controller:
ViewBag.UserName = "Alice";
In the View:
<p>Hello, @ViewBag.UserName!</p>
Which should you choose?
Both ViewData and ViewBag share the same underlying storage. If you set a value in ViewData["Key"], you can retrieve it via ViewBag.Key, and vice versa.
The primary difference is developer preference: ViewData is safer for keys that might contain special characters (since it uses string keys), while ViewBag provides a more fluid, object-like experience. For complex data structures, remember that these tools are intended for small pieces of "view-specific" information rather than heavy business models. For passing primary data to a view, strongly-typed models remain the preferred architectural choice, but these techniques provide the flexibility needed for page-level metadata like headers, alert messages, or navigation labels.
Key Takeaway: Use ViewData for string-indexed access or ViewBag for cleaner dynamic access to pass small, transient bits of data from your controller to your view.