Software developer can store custom objects in a view state just as easily as regular types. However, to store an item in a view state, ASP.NET must be able to convert it into a stream of bytes. This process is called serialization. If developer’s objects aren’t serializable, he will receive an error message when he attempts to place them in a view state.
To make his objects serializable, the software developer need to add [Serializable] attribute before his class declaration:
<Serializable()>
Public Class BankCard
Public CardNumber As String
Public CardType As String
Public ExpDate As Date
‘ Constructor
Public Sub New(ByVal cNum As String, ByVal cTyp As String, ByVal cExp As Date)
CardNumber = cNum
CardType = cTyp
ExpDate = cExp
End Sub
End Class
Because the BankCard class is marked as serializable, it can be stored in view state:
‘Store card to ViewState
Public Sub Store2ViewState()
Dim bc As New BankCard(“XXXX-XXXX-XXXX-XXXX-XXXX”, “Visa”, “03-2014”)
ViewState(“CurrentBankCard”) = bc
End Sub
Software developer will need to cast his data when he retrieves it from view state:
‘Restore bank card from ViewState
Public Sub RestoreBankCard()
Dim bc As BankCard
bc = DirectCast(ViewState(“CurentBankCard”), BankCard)
End Sub