Search code examples
asp.net-mvcviewbagviewdata

Where ViewData and ViewBag reside?


Note: This is not duplicate of this question as it does not answer the question completely.

My question is where exactly it get stored when you assign a value to ViewData or ViewBag like TempData resides in Session.

Both resides in Session too?

If not then where?


Solution

  • As @SlickSim mentioned in comment, they are stored on the heap as reference types are in .net.

    ViewBag is of type dynamic but, is internally an System.Dynamic.ExpandoObject()

    It is declared like this:

    dynamic ViewBag = new System.Dynamic.ExpandoObject();
    

    which is why you can do :

    ViewBag.Foo = "Bar";
    

    Inheritance Hierarchy:

    System.Object    
        System.Dynamic.ExpandoObject
    

    For more info on ExpandoObject

    Please go through this article on Value type, reference type, heap and stack on codeproject that may help you to understand where both ViewData and Viewbag reside.

    I hope it helps!