3

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?

Community
  • 1
  • 1
Priyank Sheth
  • 2,352
  • 19
  • 32
  • 3
    Answer in question you linked clearly states that: _This happens entirely on the server side but the idea that the data is "stored" on the server is misleading. These are transient objects which only live for the lifetime of the HTTP request._ – Jojo Jul 21 '15 at 07:00
  • But my question is that it reside in session? if not there where? I am aware about the life cycle of these objects and limitations too. But where it resides that is what I am looking for. Can you answer that with more detail than the linked one ? – Priyank Sheth Jul 21 '15 at 07:03
  • both reside in session.you can check this by disabling SessionStateBehavior on your controller..have a look here http://www.c-sharpcorner.com/UploadFile/ff2f08/controlling-session-behavior-in-Asp-Net-mvc/ – Abbas Galiyakotwala Jul 21 '15 at 07:04
  • I'm not sure what "reside" means. `ViewBag` and `ViewData` are properties of `ControllerBase` class. – Jojo Jul 21 '15 at 07:04
  • @AbbasGaliyakot: the article you linked has nothing to do with ViewBag. It only shows that `Session["test"]` and `TempData["test"]` throws exceptions after session is disabled. – Jojo Jul 21 '15 at 07:08
  • @Jojo: by reside I mean to say does any variable memory created for the same? Or internally it also get stored/preserved in Session? – Priyank Sheth Jul 21 '15 at 07:10
  • 3
    The viewbag and viewdata, being properties of the controller, are stored on the heap as reference types are in .net. They aren't persisted in the session, they passed from controller to viewpage . When the request ends, so the controller is disposed and the memory addresses marked for garbage collection. – Slicksim Jul 21 '15 at 07:16

1 Answers1

4

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!

Jamie Rees
  • 7,973
  • 2
  • 45
  • 83
Nilesh Thakkar
  • 2,877
  • 1
  • 24
  • 43