2

In MVC3, with WebViewPages, there is the new property PageData which can be used to pass arguments to a parent layout page.

Unfortunately, we still have some legacy WebFormsView pages in our app and we want to have similar behavior, in being able to pass arguments to a parent master page. Is there a way to do this?

Oved D
  • 7,132
  • 10
  • 47
  • 69

2 Answers2

1

With MVC3 you can use the ViewBag to make data available to the master page.

E.g.

In View:

@{
    ViewBag.Title = "Home Page";
}

In Master Page:

<title>@ViewBag.Title</title>

Update:

Difference between PageData and ViewData

Community
  • 1
  • 1
Chris Snowden
  • 4,982
  • 1
  • 25
  • 34
  • True, but as far as I understand the ViewBag is equivalent to the ViewData, the only difference is that ViewBag's properties are set via a Dynamic object and ViewData's values are set as if its a dictionary. Is there any difference in persistence between the two? – Oved D Aug 02 '11 at 14:24
  • `ViewBag` encapsulates `ViewData` (a wrapper around it). However, this is default code generated by MVC by the way so this is the way I would follow. – Chris Snowden Aug 02 '11 at 14:28
  • Actually, I'm noticing that if I set something in ViewData in the page, it does not get passed to the master page, but if I set something in the ViewBag, it does get passed. – Oved D Aug 02 '11 at 14:29
  • That's the MVC way of doing it anyway. Linked a quick vs link about the difference of `ViewData` (`ViewBag`) and `PageData`. – Chris Snowden Aug 02 '11 at 14:31
  • Thanks, Chris. If I had more rep I'd vote your answer up. I've also traced why the ViewData is being lost. It seems like in MVC the ViewData is tied to the model, and if you have a new model the view data is reset. For example, if you call render partial and you pass another model, the ViewData is reset. My master page had a dynamic model: Inherits="System.Web.Mvc.ViewMasterPage" Removing the dynamic from this got rid of the killing of the view data. Either way, it's a safer bet to use the ViewBag. – Oved D Aug 02 '11 at 14:36
  • Yup ViewBag is the new way and you should ignore ViewData in MVC3. Please accept my answer and upvote when you have 15 rep. Enjoy and welcome to StackOverflow! I gave you a +1. – Chris Snowden Aug 02 '11 at 14:39
0

You can use the ViewBag.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964