1

Possible Duplicate:
Modifying MVC 3 ViewBag in a partial view does not persist to the _Layout.cshtml

I'm trying to set a pageTitle from a PartialView

Here is my code:

PartialView template:

@{
    ((WebViewPage)WebPageContext.Current.Page).ViewBag.Title = "Page title";
}

_Layout.cshtml:

<title> @ViewBag.Title</title>

How to do this?

CalvT
  • 3,123
  • 6
  • 37
  • 54
Anas
  • 5,622
  • 5
  • 39
  • 71

1 Answers1

6

That's not something that a partial should do. It's just not its responsibility to modify the parent view ViewBag. And in addition to that it's not possible. Quote from MSDN:

When a partial view is instantiated, it gets its own copy of the ViewDataDictionary object that is available to the parent view. The partial view therefore has access to the data of the parent view. However, if the partial view updates the data, those updates affect only the partial view's ViewData object. The parent view's data is not changed.

You could always do the workarounds shown here but please don't. Partials should not be setting any parent state. They should not know anything about the parent.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Darin, I know this is old, and you are clearly an expert. However, isn't the point of "ViewBag" to be a universal access point for "general view data"? I understand the "separation of concerns" point, but I can't think of a circumstance where the **dynamic** ViewBag in a partial needs to be unaware of the **dynamic** ViewBag in the parent view. If it was strongly-typed, yes. – LiverpoolsNumber9 Aug 30 '13 at 08:40
  • 1
    I have a wizard, and each step is a partial. I want to change the ViewBag Title based on the step I'm on without reloading the whole page, when the step + partial I'm on changes – Alan Ball Oct 23 '17 at 11:44