I want to know why we must set the serializable attribute to save an object in view state.
Also, which type of objects can we store in view state?
I want to know why we must set the serializable attribute to save an object in view state.
Also, which type of objects can we store in view state?
Types must be serializable to be placed in ViewState. ViewState is a serialized collection of objects so any serializable objects may be put in there.
ViewState
is serialized using binary serialization using ObjectStateFormatter. Quote from the documentation:
The ObjectStateFormatter class is optimized to serialize and format many common .NET Framework reference types, as well as constants. The following table lists the types that are optimized.
Array, DateTime, Int16, String, ArrayList, Double, Int32, String [], Boolean, Enum, null (Nothing), String.Empty, Byte, Hashtable, Pair, Triplet, Char, HybridDictionary, Single, Type, Color, IDictionary,
Additionally, while conventional string types and string arrays are written to and from a serialized binary writer unaltered, some strings are optimized by creating internal string tables. Strings are optimized using these tables if the string has an associated TypeConverter object or if the string is actually an instance of the IndexedString class.
Other types not listed above are binary-serialized using a BinaryFormatter object if they implement the ISerializable interface or are decorated with the SerializableAttribute attribute. The ObjectStateFormatter class is not optimized for any of these serializable types.
If the ObjectStateFormatter class encounters a type that is not serializable, an ArgumentException exception is thrown.
For an object to be binary serializable in the ViewState
it needs to be decorated with the [Serializable]
attribute. So you can put in ViewState
any object that has this attribute. Note that simple types like string, int, float, ... can also be placed in ViewState
.
Pretty much anything that is serializable. However, keep in mind that the data will be sent over the wire between the server and the web browser (and back, during postbacks), so you may want to keep the volume down, if possible.
What objects - as per Darren and Andrew - any serializable ones. Why Serializable? So that the state can be serialized like
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTY1NTgzODUwMg9kFgJmD2QWAgIDD2QWAgIBD2QWBgIBDw8WAh4EVGV4dAUXU3VwcGxpZXIgUG9y
However in practice, need to keep viewstate to a minimum as it has bandwidth / page size performance implications. Controls are the most common users of viewstate.