问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/11509996/set-a-page-title-from-a-partialview