ASP.NET Core MVC Interview Question #14
What is the difference between ViewData, ViewBag, and a strongly typed model?
MVC Fundamentals, Controllers, Views & Routing Junior Beginner
Quick Interview Answer
ViewData is a dictionary-based mechanism that stores values by string keys. ViewBag is a dynamic wrapper around ViewData that provides property-style syntax. Both are useful for small amounts of supplemental view data but provide less compile-time safety than a strongly typed model.
Detailed Explanation
ViewData is a dictionary-based mechanism that stores values by string keys. ViewBag is a dynamic wrapper around ViewData that provides property-style syntax. Both are useful for small amounts of supplemental view data but provide less compile-time safety than a strongly typed model.
A strongly typed model is preferred for the primary data required by a view because property names and types are checked by the compiler and are easier to refactor. ViewData or ViewBag can still be appropriate for small presentation values such as a page title.
Code Example
ViewData["Title"] = "Products";
ViewBag.Message = "Available products";
return View(productViewModel);