3

Really simple question.

My layout page looks like

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

The partial looks like

@{
  ViewBag.IsInternal = false;
}

Is it doing what I think it should be doing? Basically, if in the partial, ViewBag.IsInternal is set, I am able to read that set value in the layout.

tereško
  • 58,060
  • 25
  • 98
  • 150
kei
  • 20,157
  • 2
  • 35
  • 62
  • If you just need to pass a temporary value around, you could use `TempData`. I think it's persisted until the next request. – valverij May 17 '13 at 20:51
  • Also, according to [this question](http://stackoverflow.com/questions/7993263/viewbag-viewdata-and-tempdata) `ViewBag` is just a dynamic wrapper around `ViewData`, so in theory, wherever you have your `ViewData`, you should have your `Viewbag` – valverij May 17 '13 at 20:54

2 Answers2

1

No your partial view will get its own ViewBag so modifying it will have no affect to the ViewBag in your layout class.

You could, however, pass it into your partial view as a reference and modify the layout ViewBag from your partial e.g.

Layout

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

Partial

@{
   var layoutViewBag = ((dynamic)ViewData["LayoutViewBag"]);
   layoutViewBag.IsInternal = true;
 }
James
  • 80,725
  • 18
  • 167
  • 237
  • Thanks! This makes sense. I've thought that since they were being displayed in one page, there would be some variable sharing involved but I guess this wasn't the case. – kei May 21 '13 at 14:37
  • As a follow-up question, using `RenderPartial`, I would have to specifically name the partialview, but since I'm using a bunch of partials using the layout, I do not want to be specifying the name in the layout. How do I go about doi ng this? – kei May 21 '13 at 14:55
  • Actually, I might just go with the `RenderSection` route and display the section based on Partial. – kei May 21 '13 at 15:00
  • 1
    this is overkill - just use `Html.ViewContext.Controller.ViewBag` – Simon_Weaver Feb 16 '15 at 22:16
0

You can use Html.ViewContext.Controller.ViewBag to access a 'shared' ViewBag. Here's an example where I only want to include 'Pinterest' Javascript (at the bottom of the page) if I have used a Pinterest button.

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

Then of course you set it with

    Html.ViewContext.Controller.ViewBag.Pinterest = true;
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • This didn't work for me, when setting the viewbag value in a partial view in a view using a shared layout and reading it in that layout. Using breakpoints, I noticed that the value was set before it was read, but the value was lost. – R. Schreurs Apr 09 '15 at 11:18