ASP.NET会话不会在回发之间保存列表数据

时间:2016-04-29 02:59:05

标签: c# asp.net .net

我试图将一些自定义对象存储到List中,并通过Session将其存储在回发之间。但由于某种原因,List没有更新以显示在Debug或GridView上。

List<Book> booklist;
protected void Page_Load(object sender, EventArgs e) {
    if (Session["InitialBooklist"] == null) {
        booklist = new List<Book>();
        Session.Add("InitialBooklist", booklist);
    } else {
        booklist = Session["InitialBooklist"] as List<Book>;
        GridView1.DataSource = booklist;
        GridView1.DataBind();

        foreach (Book book in booklist) {
            System.Diagnostics.Debug.Write(book.ToString());
        }
    }
}

这里是方法的相应部分,它将按钮添加到表格中的一行(与GridView不同),并为其提供点击处理程序...

    TableCell addButtonCell = new TableCell();
    Button addButton = new Button();
    addButton.Text = "Add";
    addButton.Click += delegate(object sender1, EventArgs e1) {
        addButton_Click(sender1, e1, title, author, price, coverURL, ISBN, numPages, amazonURL);
    };
    addButtonCell.Controls.Add(addButton);
    row.Cells.Add(addButtonCell);

最后,点击处理程序......

public void addButton_Click(object sender, EventArgs e, String title, String author, String price, String coverURL, String ISBN, String numPages, String amazonURL) {
    booklist.Add(new Book(title, author, price, coverURL, ISBN, numPages, amazonURL));
}

2 个答案:

答案 0 :(得分:0)

请在Page_Load中添加并检查isPostBack。请尝试这样,但我还没有尝试过。

List<Book> booklist;
protected void Page_Load(object sender, EventArgs e) {

	if(!isPostBack){
		if (Session["InitialBooklist"] == null) {
			booklist = new List<Book>();
			Session.Add("InitialBooklist", booklist);
		} else {
			booklist = Session["InitialBooklist"] as List<Book>;
			GridView1.DataSource = booklist;
			GridView1.DataBind();

			foreach (Book book in booklist) {
				System.Diagnostics.Debug.Write(book.ToString());
			}
		}
	}
}

答案 1 :(得分:0)

您的网页会话&#34; readonly&#34;? 请检查您的页面属性。

我在下面做了一些修改:

List<Book> booklist;
protected void Page_Load(object sender, EventArgs e) {
    if (Session["InitialBooklist"] == null) {
        booklist = new List<Book>();
        Session.Add("InitialBooklist", booklist);
    }

if(!isPostBack){
        booklist = Session["InitialBooklist"] as List<Book>;
        GridView1.DataSource = booklist;
        GridView1.DataBind();

        foreach (Book book in booklist) {
            System.Diagnostics.Debug.Write(book.ToString());
        }
       }
}