How to store custom objects in a View state using C#

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:

public class BankCard
       public string     CardNumber;
       public string     CardType;
       public DateTime    ExpDate;
       public BankCard(string cardNumber, string cardType, DateTime expDate)
         CardNumber = cardNumber;
         CardType   = cardType;
         ExpDate    = expDate;

Because the BankCard class is marked as serializable, it can be stored in view state:

// Store card in a view state
BankCard bc = new BankCard(“XXXX-XXXX-XXXX-XXXX-XXXX”,”Visa”,”03-2014″);
ViewState[“CurrentBankCard”] = bc;

Software developer will need to cast his data when he retrieves it from view state:

//Restore bank card from view state
BankCard bc;
bc = (BankCard)ViewTstate[“CurrentBankCard”];