Karan
Karan

Reputation: 3328

Why Viewstate can contain only serializable object?

I have a simple class with some properties and other data. Untill i stick serializable attribute to the class, i cannot save the object of the class into the viewstate.

Why Viewstate can contain only serializable objects?

Upvotes: 5

Views: 10165

Answers (4)

Roja Buck
Roja Buck

Reputation: 2354

As the viewstate of a request is passed back to the browser as a serialised representation embedded within the generated page's HTML it makes sense that only serialisable objects can be placed within it (otherwise it may fail to represent that which it contains.) That viewstate is then de-serialised during the next request.

http://i.msdn.microsoft.com/dynimg/IC152667.gif gives an example of the typical

If you are using POCO's marking them as serialisable should be trivial enough. There is an excellent resource on understanding how viewstate works, what it is etc. here:

http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx

It goes into the full lifecycle of the state and gives detail about much of it's implementation and use from the prospective of a developer.

Upvotes: 6

Marino Šimić
Marino Šimić

Reputation: 7342

I think this summarizes the answer: The state goes out of control from ther Asp.Net code to the HTTP handler which does not understand your code which will go out of scope, and must serialize it in a datastore (it's that lot of garbage you see when you view the source of a asp.net page) then give it back when another postback requires it.

enter image description here

Upvotes: 1

davidsleeps
davidsleeps

Reputation: 9503

Simply because the data stored in viewstate needs to be serialized (and deserialized).

The viewstate is essentially just text, so anything stored in it needs to be able to be represented as text and to be reconstructed from that serialized text into object form.

Upvotes: 2

Henk Holterman
Henk Holterman

Reputation: 273494

Because the ViewState is serialized before it is sent to the Client.

Maybe you can store your data in the Session object instead. It depends on what your class does and how it's used.

Upvotes: 2

Related Questions