Tutorials ASP.NET Core MVC Mastery
ViewData vs ViewBag
On this page
Data Passing: ViewData, ViewBag, and the ViewModel Revolution
ViewData: The Fast Dictionary
ViewData is a dictionary of objects that is derived from the ViewDataDictionary class. It uses string keys to store data.
// In Controller
ViewData["Greeting"] = "Hello Specialist!";
// In View
<h1>@ViewData["Greeting"]</h1>
ViewBag: The Dynamic Wrapper
ViewBag is a dynamic property that is essentially a wrapper around ViewData. It allows you to use property-like syntax.
// In Controller
ViewBag.Greeting = "Hello Architect!";
// In View
<h1>@ViewBag.Greeting</h1>
The "Expert" Verdict: Stop Using Both!
If you have more than 3 years of experience, you should almost NEVER use ViewData or ViewBag. Why? Because they are **Weakly Typed**. You get zero IntelliSense and zero compile-time error checking. One typo in a string key like ViewData["Greetng"] and your site crashes in production.
The ViewModel Pattern (12-Year Standard)
Always create a dedicated class for your view. This ensures 100% type safety and makes your views extremely clean.
public class UserDashboardViewModel {
public string UserName { get; set; }
public List RecentOrders { get; set; }
}
Senior Pro-Tip #99: TempData Persistence
Did you know that TempData data is deleted as soon as it is read? If you need it to persist for another redirect, you MUST call TempData.Keep(). This is a common bug in shopping cart checkout flows!