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 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>
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.
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; }
}
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!