Storing and Retrieving Objects from View State - The Serializable Attribute

View State allows you to retain page property values, such as string and numeric types, between postbacks. You may also store class objects in View State, but you must first add the Serializable attribute. If you do not add the Serializable attribute, you will receive this error when trying to add the object to View State:

Type 'SuchAndSuch.ThisAndThat' in Assembly 'SuchAndSuch, Version 1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable. 

Here is an example of adding Serializable to a class:

<Serializable()>_
Public Class aMenu
   Public MenuName As String
   Public MenuId as Integer
   Public Url as String

  Public Sub New(ByVal menuName as String, ByVal menuId as Integer, ByVal url as String)

   MenuName = menuName
   MenuId = menuId
   Url = url

  End Sub

End Class


The aMenu class can now be added to View State:

Dim myMenu as New aMenu("Home",1,"/default.aspx")
ViewState("myMenu") = myMenu

To use the aMenu object:

If ViewState("myMenu") IsNot Nothing then
   Dim myMenu as aMenu
   myMenu = DirectCast(ViewState("myMenu"),aMenu)
End If

May your dreams be in ASP.NET!

Nannette Thacker

No Comments