What is the difference between the Page and ViewBag dynamic objects in MVC3?
.net, asp.net-mvc, asp.net-mvc-3, c#
Solution
`Page` and `ViewBag` are dynamic and they are wrapper around dictionaries.
`Page` is the dynamic wrapper around `PageData` dictionary. `ViewBag` is the dynamic wrapper around `ViewData` dictionary.
When talk about differences,
`ViewBag` is used to share data between controller and view or even we can use to share data between a main view and partial view. So the ViewBag can be accessed from both the controllers and views.
`Page` is a little different thing, it can't be accessed from controllers and it is used to pass data between a main page and a partial page.
See an example here of using `Page` to pass data between a main view and partial view.
Main.cshtml
@{
Page.Name = "Mark;
}
@RenderPage("DisplayName.cshtml"); // partial view
DisplayName.cshtml
<p>
Name: @Page.Name
</p>
Not that I'm using the `RenderPage` to render the partial view also the partial view is located in the same directory where the main view is located.
Problem
A dynamic object `Page` can be found in `System.Web.WebPages.WebPageBase`, the abstract class which `WebViewPage` inherits from. A dynamic object `ViewBag` can be found in `System.Web.Mvc.WebViewPage`. Both can propagate up from a view to it's layout page. The other difference I can see is that `ViewBag` can be used in the Controller, whereas `Page` is only available in the view. Are there any other differences I should know about?