如何让我的ViewContext.ViewBag与我的代码一起使用?

时间:2014-05-16 21:18:12

标签: asp.net-mvc-3

我正在尝试创建一个允许我跨父视图和子视图进行通信的HtmlHelper。我从这里得到了教程:https://gist.github.com/primaryobjects/8442193

首先,我创建了这样的类和方法:

  namespace SchoolIn.Helpers
  {
     public  static class ViewBagHelpers
     {

    public static dynamic GetPageViewBag(this HtmlHelper html)
    {
        if (html == null || html.ViewContext == null) //this means that the page is root or parial view
        {
            return html.ViewData;
        }

        ControllerBase controller = html.ViewContext.Controller;

        while (controller.ControllerContext.IsChildAction)  //traverse hierachy to get root controller
        {
            controller = controller.ControllerContext.ParentActionViewContext.Controller;
        }

             return controller.ViewBag;
         }



     }
 }

在子视图中,我添加了一个using语句:

  @using SchoolIn.Helpers

 @{Html.GetPageViewBag().PageTitle = "My Custom Property Readable By Parent View"; }

在父视图中,我正在尝试这样做:

 @{ ViewBag.Title = ViewContext.ViewBag.PageTitle }

所以我想我有两个问题。第一个是我没有像教程那样访问html.ViewBag而在父视图中我无法访问...

  ViewContex.ViewBag.

知道如何让这项工作成功吗?谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

经过几次调整后,我设法让它工作了。确保语法正确,并在渲染部分后设置标题。

布局页面(_Layout.cshtml):

@using SchoolIn.Helpers

@* Nb. The example did not include the call to partial. *@
@Html.Partial("_Child")

@* The following line must appear after the partial is rendered for the ViewBag to have been set. *@
@* Nb. The example was missing the semicolon. *@
@{ ViewBag.Title = ViewContext.ViewBag.PageTitle; }

部分视图(_Child.cshtml):

@using SchoolIn.Helpers

@{Html.GetPageViewBag().PageTitle = "My Custom Property Readable By Parent View"; }