5

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?

ChrisWue
  • 18,612
  • 4
  • 58
  • 83
Karan
  • 3,265
  • 9
  • 54
  • 82
  • The (default) ASP.NET serializes just work that way. There are other serialization identification techniques (e.g. DataContracts), but only Serializable-annotated types are supported by LosFormatter (older) and ObjectStateFormatter. (Although, ISerializable might also work, but I've never tried it.) –  Dec 14 '12 at 06:10

4 Answers4

6

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.

Roja Buck
  • 2,354
  • 16
  • 26
2

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.

H H
  • 263,252
  • 30
  • 330
  • 514
2

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.

davidsleeps
  • 9,393
  • 11
  • 59
  • 73
1

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

Marino Šimić
  • 7,318
  • 1
  • 31
  • 61