2011-03-17 19 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事件嗎?

相關問題