[英]How to save an array in the ViewState and be able to retrieve it AFTER the page has unloaded?
采取以下代码:
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,因为“ CustomerList = new List<Customer>((Customer[])ViewState["Customers"]);
”,因为它不在ViewState中。 这是为什么?
Page Unload太迟了,无法设置ViewState变量
从http://msdn.microsoft.com/en-us/library/ms178472.aspx :
页面完全呈现,发送给客户端并准备丢弃后,将引发Unload事件。 此时,将卸载诸如响应和请求之类的页面属性,并执行清理。
ViewState本身作为页面中的隐藏字段发送-因此,如果您已经将页面发送给客户端,则以后就无法添加到ViewState。
尝试使用LoadComplete或PreRender事件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.