Asp.net 基础9(状态管理之Session,实例购物车简单代码)
2010-05-15 13:49 c#在路上 阅读(2544) 评论(0) 编辑 收藏 举报Session 请求与客户有关系, 每个客户都有自己的Session。应用到比如,购物车等方面。
初始化Session。在每一个session加入时,初始化内容。

public class Global : System.Web.HttpApplication
{
//...
protected void Session_Start(object sender, EventArgs e)
{
//初始化,购物车session
Session["Cart"] = new ArrayList();
Logger.Log(string.Format("会话加入:{0}",Context.Session.SessionID));
}
}
{
//...
protected void Session_Start(object sender, EventArgs e)
{
//初始化,购物车session
Session["Cart"] = new ArrayList();
Logger.Log(string.Format("会话加入:{0}",Context.Session.SessionID));
}
}
购买铅笔的页面:

public partial class BuyPencileForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList arry = (ArrayList)Session["Cart"];
arry.Add(new Cart("Pencile", 10));
}
}
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList arry = (ArrayList)Session["Cart"];
arry.Add(new Cart("Pencile", 10));
}
}
购买钢笔的页面:

public partial class BuyRedPenForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
//结算:
Response.Redirect("TotalForm.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList arry = (ArrayList)Session["Cart"];
arry.Add(new Cart("RedPeng", 30));
}
}
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
//结算:
Response.Redirect("TotalForm.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
ArrayList arry = (ArrayList)Session["Cart"];
arry.Add(new Cart("RedPeng", 30));
}
}
结算页面:

public partial class TotalForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int totalCount = 0;
ArrayList list = (ArrayList)Session["Cart"];
foreach (Cart item in list)
{
totalCount += item.Cost;
Response.Output.WriteLine(string.Format("货物名称:{0},货物价格:{1}", item.Description, item.Cost.ToString()));
Response.Output.WriteLine("<br />");
}
Response.Output.WriteLine(string.Format("总数:{0}",totalCount.ToString()));
}
}
购买页面时在session加入变量,结算页面读取Session。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步