All answers suggest that ViewBag
and/or ViewData
is to pass data from Controller
to Views
which is misinformation. both are very useful to pass data from Views to Layout or Partial to Views (or ViewComponents, etc) It's not controller exclusive.
as the default asp.net sample have this in the layout page:
<title>@ViewData["Title"] - MyApp</title>
and in any view
ViewData["Title"] = "Details";
So then, to asking the question: "what's the difference between ViewBag
and ViewData
?"
The most notable difference is ViewData
is a Strongly Typed Dictionary while
ViewBag
is a dynamic type.
Note that the data inside IS THE SAME
ViewData["Title"] = "MyTitle";
ViewBag.Title; // returns "MyTitle";
When to use one or another?
ViewBag
doesn't support not valid C# names.
you can't access ViewData["Key With Space"]
with ViewBag
ViewBag.Something
is dynamic and you may have problems when calling methods (like extension methods) that needs to know the exact parameter at compile time.ViewBag
can check for nulls syntactical cleaner: ViewBag.Person?.Name
ViewData
have all the properties of a Dictionary like ContainsKey
, Add
, etc. so you can use ViewData.Add("somekey", "somevalue")
keep in mind it might throw exceptions.ViewData
on views needs TypeCasting while ViewBag
don't.Knowing the subtle differences, using one or another is much more a taste preference.
Normally you can think of ViewBag.AnyKey
to an alias of ViewData["AnyKey"]