我是asp新的品牌,所以我认为这个答案应该是一个简单的方法,但我无法弄清楚我做错了什么。这是一个非常简单的购物车练习,我正在学习ASP。我创建了会话,添加了一些内容,然后在结帐页面上可以逐个删除购物车中的物品。如果我点击删除,该项目将从列表框中删除,但不会从会话中删除。我知道它在会话中仍然存在,因为如果我点击链接到购物页面,购物页面上的列表框将填充我认为已删除的项目。从会话索引(ASP)中删除字典条目
我试着去除它两种不同的方式,我不知道为什么它不工作。
注意:字典键是用于填充列表框的产品的实际名称。值条目是我现在没有实际使用的productID#。购物页面上的列表框正在填充来自sqlsource的数据。 SelectedItem.Text =产品名称(显示内容)和SelectedValue = productID(未使用)。
非常感谢您的帮助
//Default (shopping) page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Create a new collection for the session indexer
ArrayList cart = (ArrayList)Session["scart"];
//Need to initialize a new object in case it's null
if (cart == null)
{
cart = new ArrayList();
Session["scart"] = cart;
}
//Show the shopping car listbox if there are items in it and the
//user returned from the checkout page
else pnlItems.Visible = true;
foreach (DictionaryEntry item in cart)
{
lbItems.Items.Add((string)item.Key);
}
}
//Show the shipping cart listbox containing the items the user just added
if (IsPostBack) pnlItems.Visible = true;
}
private void add_to_cart(string item, int value)
{
//Method to add the selected item to the collection/session indexer
ArrayList cart = (ArrayList)Session["scart"];
cart.Add(new DictionaryEntry(item, value));
}
protected void btnAddItem_Click(object sender, EventArgs e)
{
//Method to send the selected item to the add_to_cart method
string item = ddlProducts.SelectedItem.Text;
lbItems.Items.Add(item);
int value = int.Parse(ddlProducts.SelectedValue);
add_to_cart(item, value);
}
protected void ddlProducts_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnCheckOut_Click(object sender, EventArgs e)
{
//Send the user to the checkout page when the button is clicked
Response.Redirect("checkout.aspx", true);
}
}
//CheckoutPage:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Populate the shopping cart on the checkout page with the items in the collection
ArrayList cart = (ArrayList)Session["scart"];
foreach (DictionaryEntry item in cart)
{
lbCheckOut.Items.Add((string)item.Key);
}
}
}
protected void btnKillOrder_Click(object sender, EventArgs e)
{
//Kills the order by ending the session, then returns the user to the shopping page.
Session.Clear();
Response.Redirect("Default.aspx", true);
}
protected void btnRemove_Click(object sender, EventArgs e)
{
//Removes the selected item from the shopping cart listbox and the session indexer
ArrayList cart = (ArrayList)Session["scart"];
cart.Remove(lbCheckOut.SelectedItem.Text);
lbCheckOut.Items.Remove(lbCheckOut.SelectedItem.Text);
Session["scart"] = cart;
//Session.Remove(lbCheckOut.SelectedItem.Text);
}
}
谢谢,这个工作!我曾尝试类似于此前的东西,但在foreach语句中出现枚举器错误。不知道如何进行调试,我放弃了并尝试了上面提到的方法。无论如何,谢谢! – 2010-11-26 19:19:23