【ASP】session實現購物車
阿新 • • 發佈:2019-01-14
1.問題提出
利用session內建物件,設計並實現一個簡易的購物車,要求如下:
1)利用使用者名稱和密碼,登入進入購物車首頁
2)購物首頁顯示登入的使用者名稱以及該使用者是第幾位訪客。(同一使用者的重新整理應該記錄為1次)
3)購物頁面分為兩個部分:家用電器和運動系列,選擇商品種類進行購物。
4)在每個具體的購物頁中,如果使用者已經選擇了商品,當再次進入到該頁時要顯示已選中的商品。
5)選好商品可以檢視購物車,購物車中有繼續購物,清空購物車。
2.設計實現思路
1)登入
1 protected void Button1_Click(object sender, EventArgs e) 2 { 3 string a = TextBox1.Text; 4 string b = TextBox2.Text; 5 6 if (a.Equals("yitou") && b.Equals("111")) 7 { 8 Application["name"] = TextBox1.Text; 9 Response.Redirect("welcome.aspx"); 10 } 11 12 }
介面設計
2)web.config中設定session
在Global.asax中設定初始訪問次數為0。利用session_start,保證使用者數登入加1.
1void Application_Start(object sender, EventArgs e) 2 { 3 // 在應用程式啟動時執行的程式碼 4 RouteConfig.RegisterRoutes(RouteTable.Routes); 5 BundleConfig.RegisterBundles(BundleTable.Bundles); 6 Application["count"] = 0; 7 } 8 void Session_Start(object sender, EventArgs e) 9 { 10 Application["count"] = (int)Application["count"] + 1; 11 }
welcome.asp
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 4 string s = Application["name"].ToString(); 5 Response.Write("歡迎" + s + "登入該頁面,您是第"+Application["count"].ToString()+"個使用者"); 6 7 } 8 protected void Button1_Click(object sender, EventArgs e) 9 { 10 if (RadioButton1.Checked) 11 { 12 Server.Transfer("goods.asp"); 13 } 14 if (RadioButton2.Checked) 15 { 16 Server.Transfer("sports.asp"); 17 } 18 }
介面設計
3)如果選擇運動介面
4)在每個具體的購物頁中,如果使用者已經選擇了商品,當再次進入到該頁時要顯示已選中的商品。
5)選擇好商品,可以檢視購物車中的內容:
1 protected void Page_Load(object sender, EventArgs e) 2 { 3 Label1.Text = "電器:"; 4 Label2.Text = "運動:"; 5 int num=0; 6 List<string> str = (List<string>)Session["goods"]; 7 if (str != null) 8 { 9 for (int i = 0; i < str.Count; i++) 10 { 11 Label1.Text += " " + str[i]; 12 } 13 } 14 else num++; 15 List<string> sports = (List<string>)Session["sports"]; 16 if (sports != null) 17 { 18 for (int i = 0; i < sports.Count; i++) 19 { 20 Label2.Text += " " + sports[i]; 21 } 22 } 23 else num++; 24 if (num == 2) 25 { 26 Label3.Text = "購物車是空的,快去購物"; 27 28 } 29 else 30 Label3.Text = "購物車裡面有:"; 31 }
6)檢視購物車時,如果沒有購物,則會給予提示。
清空購物車:
protected void Button1_Click(object sender, EventArgs e) { Label3.Text = "購物車是空的,快去購物"; Label1.Text = ""; Label2.Text = ""; }
3.總結
利用session儲存物件,後期再修改一下做成資料庫的。