Set a page title from a PartialView [duplicate]

跟風遠走 提交于 2020-01-03 01:59:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!