3

很简单的问题。

我的布局页面看起来像

@RenderBody()
@{
  if (ViewBag.IsInternal)
  {
    //do something here
  }
}

部分看起来像

@{
  ViewBag.IsInternal = false;
}

它在做我认为应该做的事吗?基本上,如果在部分中设置了 ViewBag.IsInternal,我可以在布局中读取该设置值。

4

2 回答 2

1

没有您的局部视图将获得自己的 ViewBag,因此修改它不会影响您布局类中的 ViewBag。

但是,您可以将其作为参考传递到您的局部视图中,并从您的局部视图中修改布局 ViewBag,例如

布局

@{Html.RenderPartial("PartialView", Model, new ViewDataDictionary { {"LayoutViewBag", ViewBag}});

部分的

@{
   var layoutViewBag = ((dynamic)ViewData["LayoutViewBag"]);
   layoutViewBag.IsInternal = true;
 }
于 2013-05-17T22:54:29.903 回答
0

您可以使用Html.ViewContext.Controller.ViewBag来访问“共享”的 ViewBag。这是一个示例,如果我使用了 Pinterest 按钮,我只想包含“Pinterest”Javascript(在页面底部)。

 if (Html.ViewContext.Controller.ViewBag.Pinterest == true)
 {
      <text>
         <script type="text/javascript" async defer src="//assets.pinterest.com/js/pinit.js"></script>
      </text>
 }

然后当然你设置它

    Html.ViewContext.Controller.ViewBag.Pinterest = true;
于 2015-02-16T22:15:45.710 回答