Set a page title from a PartialView [duplicate]
Asked Answered
P

1

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?

Pry answered 16/7, 2012 at 18:8 Comment(2)
#4974527Timmerman
I've already visited it, but I'm looking for a more "convinient" solution!!Pry
G
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.

Glynas answered 16/7, 2012 at 20:51 Comment(2)
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.Corduroy
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 changesEncarnalize

© 2022 - 2024 — McMap. All rights reserved.