Pushing a Geneic List of <T> to View state

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?




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值