I am reading a book on ASP.NET MVC and I'm wondering how the following example works:
Example #1
Controller
public class MyController : Controller
{
public ActionResult Index()
{
ViewBag.MyProperty = 5;
return View();
}
}
View
<h1>@ViewBag.MyProperty</h1>
Now I understand that ViewBag
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 ViewBag
from the controller, even though we don't pass anything directly?
I thought that the ViewBag
could be a public
static
object, but then any change to it would be global and it wouldn't be specific to a view instance.
Could you elaborate as to how this works behind the scenes?
Example #2
Controller
public class MyController : Controller
{
public ActionResult Index()
{
ViewBag.MyProperty = 5;
return View();
}
public ActionResult Index2()
{
ViewBag.MyProperty = 6;
return View();
}
}
Now let's say the Index
method is called first, and then the Index2
. In the end the value of ViewBag.MyProperty
will end up as 6 (the value from Index2
). 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. Is this the case?
ViewBag
object is simply instantiated with the controller object as an instance property (notstatic
). – ChronometryViewBag
instance, it can affect each other? Wouldn't that cause a problem? I feel that I'm still thinking in desktop development though. – ErythriteIndex()
is called, and disposed afterreturn View();
is executed. SoViewBag
goes out of scope once the entire request is completed. That's why theViewBag
properties do not persist across requests. – Chronometryobject
property. I suspect that it is anExpandoObject
. – ChronometryExpandObject
couple minutes ago somewhere, let me see. – ErythriteExpandoObject
is cool. It implementsIEnumerable
, so all of the Linq methods work on it. – ChronometryExpandObject
, but unfortunately he didn't cite his resource. @AndreCalil, you are right that it is completely different than desktop development. I'm just trying to wrap my mind around it and change my mindset. – ErythriteController
inheritsControllerBase
that has thepublic dynamic ViewBag { get; }
property – Tanney