view - 在局部 View 中修改 MVC 3 ViewBag 不会持久化到 _Layout.cshtml

标签 view asp.net-mvc-3 razor partial viewbag

我将 MVC 3 与 Razor View 引擎一起使用。我想在局部 View 内的 ViewBag 中设置一些值,并希望在我的 _Layout.cshtml 中检索这些值。例如,当您设置默认的 ASP.NET MVC 3 项目时,您会在“/Views/Shared”文件夹中获得一个 _Layout.cshtml 文件。在 _Layout.cshtml 中,页面标题设置如下:

<title>@ViewBag.PageTitle</title>

然后在“/Views/Home/About.cshtml” View 中修改ViewBag的内容:
@{
    ViewBag.Title = "About Us";
}

这工作正常。当“关于” View 呈现时,页面标题是“关于我们”。所以,现在我想在我的 About View 中渲染一个 Partial View ,我想修改我的 Partial View 中的 ViewBag.Title。 (“/Views/Shared/SomePartial.cshtml”)
@Html.Partial("SomePartial")

在此部分 View 中,我有以下代码:
@{
    ViewBag.Title = "About Us From The Partial View";
}

当我调试这段代码时,我看到 ViewBag.Title 被设置为“关于我们”,然后在部分 View 中我看到它被重置为“关于我们来自部分 View ”,但是当代码点击 _Layout.cshtml 时它会回到“关于我们”。

这是否意味着如果在 Partial View 中修改了 ViewBag 的内容,这些更改将不会出现(可访问)在主 View (About.cshtml) 或 _Layout.cshtml 中?

提前致谢!

最佳答案

我也有这个问题,找不到任何简洁明了的解决方案。

我想出的解决方案是实现一个 Html 扩展方法,该方法返回您定义的“PageData”类,其中包含您需要的任何数据:

    [ThreadStatic]
    private static ControllerBase pageDataController;
    [ThreadStatic]
    private static PageData pageData;

    public static PageData GetPageData(this HtmlHelper html) {
        ControllerBase controller = html.ViewContext.Controller;
        while (controller.ControllerContext.IsChildAction) {
            controller = controller.ControllerContext.ParentActionViewContext.Controller;
        }
        if (pageDataController == controller) {
            return pageData;
        } else {
            pageDataController = controller;
            pageData = new PageData();
            return pageData;
        }
    }

它查找当前请求的顶级 Controller ,并在每次在同一 HTTP 请求中调用该方法时返回相同的 PageData 对象。它在新的 HTTP 请求中第一次被调用时创建一个新的 PageData 对象。

关于view - 在局部 View 中修改 MVC 3 ViewBag 不会持久化到 _Layout.cshtml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4974027/

相关文章:

jquery - 停止 Visual Studio 提示 Razor 和 JQuery

razor - ReSharper 支持自定义 Razor 指令

jquery - 单击 Html.ActionLink + MVC4 打开 jQuery 对话框

view - 如何开始使用 Kostache?

android - 使用 Path 绘制圆形扇区

asp.net-mvc-3 - MVC3 无法识别 Razor View 中的 MvcContrib 命名空间

asp.net-mvc-3 - ASP.NET MVC 3 _Layout.cshtml Controller

Eclipse RCP应用程序日志 View : change/set TimeZone for messages sent to the Eclipse Log view

android - 根据 Android 中的屏幕大小动态添加 View

c# - 在某些情况下禁用 Required 验证属性