21

I have a specific ViewBag property that I would like to set at the ViewStart level. Ideally, I would like to be able to override that property on a page basis, if necessary. Is this possible? If so, how do I access the ViewBag property within a ViewStart page?

Jim Geurts
  • 19,124
  • 23
  • 91
  • 105

1 Answers1

12

There are two way to do this:

  1. Use the PageData property (it's something more applicable to ASP.NET WebPages and seldom used in MVC)

    • Set:

      @{
          PageData["message"] = "Hello";
      }
      
    • Retrieve

      <h2>@PageData["message"]</h2>
      
  2. Try to find the view instance (the code is a bit dirty, but it does give you access directly to ViewBag/ViewData

    • Set:

      @{
          var c = this.ChildPage;
          while (c != null) {
              var vp = c as WebViewPage;
              if (vp != null) {
                  vp.ViewBag.Message = "Hello1";
                  break;
              }
              c = c.ChildPage;
          }
      }
      
    • Retrieve: as per usual

      <h2>@ViewBag.Message</h2>
      
marcind
  • 52,124
  • 12
  • 121
  • 111
  • That's unfortunate. An action filter doesn't make sense for my situation. I wanted to set a property that tells the layout which menu is active. I guess I'll just add the property to each page. – Jim Geurts Jan 29 '11 at 00:54
  • @Jim I was too quick. See revised answer. – marcind Jan 29 '11 at 02:07
  • ViewPage is analogous to SessionVar that's sticky to the page instead of session? – justSteve Jan 29 '11 at 03:51
  • More like request context items, but sure it's specific to the view page hierarchy. – marcind Jan 29 '11 at 05:47
  • #2 is an interesting solution... it does feel really dirty, but would get the job done. Maybe I could wrap that in an extension method to make me feel better about it. :) – Jim Geurts Jan 30 '11 at 16:27
  • 1
    Doesn't work, I get an error: 'System.Web.WebPages.WebPageRenderingBase' does not contain a definition for 'ChildPage' and no extension method 'ChildPage' accepting a first argument of type 'System.Web.WebPages.WebPageRenderingBase' could be found (are you missing a using directive or an assembly reference?) – jjxtra Jul 22 '11 at 02:54
  • I am also experiencing PsychoDad's problem, ASP.NET MVC 4 Beta – Erin Drummond Mar 20 '12 at 02:28
  • For mvc3 fit `ViewContext.Controller.ViewData("Title") = "My title"` – Berat Bilgin Jun 20 '12 at 09:09
  • @jjxtra - I was able to get method 2 working by changing `while` to `if` and removing `c = c.ChildPage;` and `break;` Thanks @marcind! – Timothy Kanski Dec 08 '16 at 22:14