现在我有一个CheckBoxList,它根据用户的搜索动态填充信息。在用户检查列表中的项目并按下按钮后,我想将该项目添加到在回发之间保存的列表中。我(想)我已正确创建了一个会话并保存了一个列表,但我需要知道如何正确地添加到该列表中。对ASP.NET来说还是一个新手。
List<Book> currentBookSelection;
List<Book> finalBooklist;
protected void Page_Load(object sender, EventArgs e) {
if (Session["booklist"] == null) {
finalBooklist = new List<Book>();
Session.Add("booklist", finalBooklist);
System.Diagnostics.Debug.Write("FINAL Booklist Session created.");
} else {
finalBooklist = Session["booklist"] as List<Book>;
System.Diagnostics.Debug.Write("FINAL Booklist Session ALREADY created.");
System.Diagnostics.Debug.Write("Number of books in FINAL: " + finalBooklist.Count());
}
currentBookSelection = new List<Book>();
}
下一部分是用于通过forloop为保存为字符串的复选框上的每个项目提取信息(保存为字符串)的方法的片段 - 并添加到自定义类的对象中。
cblResults.Items.Add(bookTitle);
currentBookSelection.Add(new Book(bookTitle, bookAuthor, bookPrice, bookCoverURL, bookISBN, bookNumPages, bookAmazonURL));
最后,当用户按下按钮时......如果用户选中一个框,则在currentBookSelection中找到具有相同标题的对象,然后将该对象添加到finalBooklist中 - 这应该在刷新/回发之间保持不变。 / p>
protected void btnAddSelected_Click(object sender, EventArgs e) {
foreach (ListItem item in cblResults.Items) {
if (item.Selected) {
foreach (Book book in currentBookSelection) {
if (book.title == item.Text) {
finalBooklist.Add(book);
System.Diagnostics.Debug.Write(book.title + " added to FinalBooklist");
}
}
}
}
System.Diagnostics.Debug.Write("Button click event finished.");
cblResults.Items.Clear();
}
解决方案:我不得不将当前的BookSelection保存到会话中 - 否则当我按下按钮时,它只会返回到大小0.感谢@Steve和其他人的帮助!
protected void Page_Load(object sender, EventArgs e) {
if (Session["finalbooklist"] == null) {
finalBooklist = new List<Book>();
Session.Add("finalbooklist", finalBooklist);
System.Diagnostics.Debug.Write("FINAL Booklist Session created.");
} else {
finalBooklist = Session["finalbooklist"] as List<Book>;
System.Diagnostics.Debug.Write("Number of books in FINAL: " + finalBooklist.Count());
PrintFinalBookList();
}
if (Session["currentbooklist"] == null) {
currentBookSelection = new List<Book>();
Session.Add("currentbooklist", currentBookSelection);
System.Diagnostics.Debug.Write("CURRENT Booklist created");
} else {
currentBookSelection = Session["currentbooklist"] as List<Book>;
System.Diagnostics.Debug.Write("Number of books in CURRENT: " + currentBookSelection.Count());
}
}