3

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?

smdrager
  • 7,327
  • 6
  • 39
  • 49
  • http://stackoverflow.com/questions/6429079/what-is-the-difference-between-viewdata-pagedata-in-asp-net-mvc-3 – VJAI May 30 '12 at 13:10

1 Answers1

6

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.

VJAI
  • 32,167
  • 23
  • 102
  • 164
  • It may help to point out that `ViewBag` is a property of *both* `WebViewPage` and `ControllerBase` and the data from one is copied into the other. – Michael Edenfield May 30 '12 at 13:58
  • @MichaelEdenfield Can you please elaborate your comment.As how does it get copied into other. – Abi May 23 '17 at 07:16