Working on a DotNetNuke Project we had a requirement which was pretty .NET'ish and had nothing to do with DotNetNuke. All we wanted to do was to store a Generic list of <T> in the view state - where <T> was a XXX_Info class we usually write for DNN module.

For Any information to be retained in the view state it was obviously implied that it had to be serialized. If you're looking for some fairly complicated code to manually serialize Generic Classes you probably want to go here: http://www.devx.com/dotnet/Article/30158/0/page/2

Here's another quick way if you just wanted to Save things to the view state:

  1. Mark the Class (and all parent classes if any) whose List you want to store in the viewstate as [Serializable].
  2. Convert the List to an Array.
  3. Store In View State.

Reconvert to List when reading from Viewstate.

Here's some quick sample code that illustrates:

   13     protected void Page_Load(object sender, EventArgs e)

   14     {

   15         // Quickly Illustrate  Creation of a List of that contains information;

   16         List<Customer> CustomerList = new List<Customer>();

   17         Customer SingleCustomer = new Customer();

   18         SingleCustomer.CustomerName = "foo";

   19         CustomerList.Add(SingleCustomer);

   20 

   21         // Convert the List to Array of Customers and Save To View State

   22         // Rather than Handling Serialization Manually

   23         ViewState.Add("Customers", CustomerList.ToArray());

   24 

   25         // While Reading the View State Information - Of course

   26         // use correct checks to see the item is Not Null and All that... and then do:

   27         Customer[] newArray = (Customer[])ViewState["Customers"];

   28 

   29         List<Customer> newList = new List<Customer>(newArray);

   30         Response.Write(CustomerList[0].CustomerName);

   31 

   32     }

   33 

   34     [Serializable]

   35     public class Customer

   36     {

   37         private string _CustomerName;

   38         public int CustomerName

   39         {

   40             get  { return _CustomerName;  }

   41             set  { _CustomerName = value; }

   42         }

   43     }


Pretty basic technique - which you definitely should NOT be using if the data volume in you collection item is Large - but works for scenarios where you want to save a small Generic List (3-10 odd items) to View State. Any other elegant ways of doing this?