2011-03-17 15 views
0

看看下面的代码:如何在ViewState中保存数组并在页面卸载后能够检索它?

using System; 
using System.Collections; 
using System.Configuration; 
using System.Data; 
using System.Linq; 
using System.Web; 
using System.Web.Security; 
using System.Web.UI; 
using System.Web.UI.HtmlControls; 
using System.Web.UI.WebControls; 
using System.Web.UI.WebControls.WebParts; 
using System.Xml.Linq; 
using System.Collections.Generic; 

namespace Test 
{ 
    public partial class _Default : System.Web.UI.Page 
    { 
     private List<Customer> CustomerList; 
     protected void Page_Load(object sender, EventArgs e) 
     { 
      // Quickly Illustrate Creation of a List of that contains information; 
      //CustomerList = (!this.IsPostBack) ? new List<Customer>() : new List<Customer>((Customer[])ViewState["Customers"]); 
      if (IsPostBack) 
       CustomerList = new List<Customer>((Customer[])ViewState["Customers"]); 
      else 
       CustomerList = new List<Customer>(); 
      // Convert the List to Array of Customers and Save To View State 
      // Rather than Handling Serialization Manually 
      //ViewState.Add("Customers", CustomerList.ToArray()); 

      // While Reading the View State Information - Of course 
      // use correct checks to see the item is Not Null and All that... and then do: 
      //Customer[] newArray = (Customer[])ViewState["Customers"]; 
      //List<Customer> newList = new List<Customer>(newArray); 
      //for (int i = 0; i < CustomerList.Count; i++) 
      // Response.Write(CustomerList[i].CustomerName + "\r\n"); 

     } 

     protected void Page_Unload(object sender, EventArgs e) 
     { 
      for (int i = 0; i < CustomerList.Count; i++) 
       Response.Write(CustomerList[i].CustomerName + "\r\n"); 
      ViewState.Add("Customers", CustomerList.ToArray()); 
     } 

     protected void Button1_Click(object sender, EventArgs e) 
     { 
      Customer SingleCustomer = new Customer(); 
      SingleCustomer.CustomerName = TextBox1.Text; 
      CustomerList.Add(SingleCustomer); 
      ViewState.Add("Customers", CustomerList.ToArray()); 
     } 
    } 
} 

它不工作。每次点击添加按钮并重新加载页面时,我都会得到一个NullReferenceException,因为它不在ViewState中。“CustomerList = new List<Customer>((Customer[])ViewState["Customers"]);”这是为什么?

回答

5

页卸载根本来不及设置的ViewState变量

http://msdn.microsoft.com/en-us/library/ms178472.aspx

卸载事件引发后 页面已经被完全呈现,发送到 客户端,是准备被丢弃 。在这一点上,页面 属性,如Response和 请求被卸载,清理是 执行。

ViewState本身作为隐藏字段发送到页面 - 所以如果您已经将页面发送到客户端,那么您以后不能添加到ViewState中。

请尝试LoadComplete或PreRender事件吗?

相关问题