title: How does ViewBag in ASP.NET MVC work behind the scenes?
body: <p>I am reading a book on ASP.NET MVC and I'm wondering how the following example works:</p>
  
  <h2>Example #1</h2>
  
  <h3>Controller</h3>
  
  <pre><code>public class MyController : Controller
  {
      public ActionResult Index()
      {
          ViewBag.MyProperty = 5;
  
          return View();
      }
  }
  </code></pre>
  
  <h3>View</h3>
  
  <pre><code>&lt;h1&gt;@ViewBag.MyProperty&lt;/h1&gt;
  </code></pre>
  
  <p>Now I understand that <code>ViewBag</code> is a dynamic object, so that's how you can set the property (though I don't know much about dynamic objects, never worked with them.) But how does the view get the specific instance of the <code>ViewBag</code> from the controller, even though we don't pass anything directly?</p>
  
  <p>I thought that the <code>ViewBag</code> could be a <code>public</code> <code>static</code> object, but then any change to it would be global and it wouldn't be specific to a view instance.</p>
  
  <p>Could you elaborate as to how this works behind the scenes?</p>
  
  <h2>Example #2</h2>
  
  <h3>Controller</h3>
  
  <pre><code>public class MyController : Controller
  {
      public ActionResult Index()
      {
          ViewBag.MyProperty = 5;
  
          return View();
      }
  
      public ActionResult Index2()
      {
          ViewBag.MyProperty = 6;
  
          return View();
      }
  }
  </code></pre>
  
  <p>Now let's say the <code>Index</code> method is called first, and then the <code>Index2</code>. In the end the value of <code>ViewBag.MyProperty</code> will end up as 6 (the value from <code>Index2</code>). I feel that it is not a good thing to do, but at the same time I feel that I'm thinking in desktop development terms. Maybe it doesn't matter when used with ASP.NET MVC, as the web is stateless. <strong>Is this the case?</strong></p>