1.问题提出
利用session内置对象,设计并实现一个简易的购物车,要求如下:
1)利用用户名和密码,登录进入购物车首页
2)购物首页显示登录的用户名以及该用户是第几位访客。(同一用户的刷新应该记录为1次)
3)购物页面分为两个部分:家用电器和运动系列,选择商品种类进行购物。
4)在每个具体的购物页中,如果用户已经选择了商品,当再次进入到该页时要显示已选中的商品。
5)选好商品可以查看购物车,购物车中有继续购物,清空购物车。
2.设计实现思路
1)登录
protected void Button1_Click(object sender, EventArgs e)
{
string a = TextBox1.Text;
string b = TextBox2.Text; if (a.Equals("yitou") && b.Equals(""))
{
Application["name"] = TextBox1.Text;
Response.Redirect("welcome.aspx");
} }
界面设计
2)web.config中设置session
在Global.asax中设置初始访问次数为0。利用session_start,保证用户数登录加1.
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Application["count"] = ;
}
void Session_Start(object sender, EventArgs e)
{
Application["count"] = (int)Application["count"] + ;
}
welcome.asp
protected void Page_Load(object sender, EventArgs e)
{ string s = Application["name"].ToString();
Response.Write("欢迎" + s + "登录该页面,您是第"+Application["count"].ToString()+"个用户"); }
protected void Button1_Click(object sender, EventArgs e)
{
if (RadioButton1.Checked)
{
Server.Transfer("goods.asp");
}
if (RadioButton2.Checked)
{
Server.Transfer("sports.asp");
}
}
界面设计
3)如果选择运动界面
4)在每个具体的购物页中,如果用户已经选择了商品,当再次进入到该页时要显示已选中的商品。
5)选择好商品,可以查看购物车中的内容:
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "电器:";
Label2.Text = "运动:";
int num=;
List<string> str = (List<string>)Session["goods"];
if (str != null)
{
for (int i = ; i < str.Count; i++)
{
Label1.Text += " " + str[i];
}
}
else num++;
List<string> sports = (List<string>)Session["sports"];
if (sports != null)
{
for (int i = ; i < sports.Count; i++)
{
Label2.Text += " " + sports[i];
}
}
else num++;
if (num == )
{
Label3.Text = "购物车是空的,快去购物"; }
else
Label3.Text = "购物车里面有:";
}
6)查看购物车时,如果没有购物,则会给予提示。
清空购物车:
protected void Button1_Click(object sender, EventArgs e)
{
Label3.Text = "购物车是空的,快去购物";
Label1.Text = "";
Label2.Text = "";
}
3.总结
利用session存储对象,后期再修改一下做成数据库的。