购物车--Session+DataTable实现(转载)
用Session实现购物车的方式很多,可以把对象保存到DataTable,Dictionary<key,value>,HashTable中,然后保存到session中,下面是使用DataTable+Session实现的购物车,为了安全合理,这里只允许注册用户使用
大概的思路是这样的:
1、数据库设计:用户表(User),商品表(Product)
2、程序使用三层实现,有UserInfo类,ProductInfo类,其中ProductInfo除了与数据库对应的属性外,还有
一个num属性,或者在添加一个购物车类ShopCar,属性有ProductInfo对象和num属性!这里采用前一个
3、根据购物车的流程写代码
实例图:
Default.aspx
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Cart.BLL;
using Cart.Models;
using System.Text;
using System.Collections.Generic;
using System.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
GetProductBind();
}
}
//绑定所有产品
public void GetProductBind()
{
dlGoodsInfo.DataSource = ProductManger.GetProductList();
dlGoodsInfo.DataBind();
}
protected void dlGoodsInfo_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "buy")
{
string P_str_GoodsID = e.CommandArgument.ToString();
int proId = Convert.ToInt32(P_str_GoodsID);
if (Session["UserID"] != null)
{
//将商品放入到购物车
//判断是否创建购物车
//不存在
if (Session["GoodsCart"] == null)
{
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("ProId", typeof(int));
DataColumn dc2 = new DataColumn("ProName", typeof(string));
DataColumn dc3 = new DataColumn("ProPrice", typeof(decimal));
DataColumn dc4 = new DataColumn("num", typeof(int));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
ProductInfo product = ProductManger.GetProduct(proId);
DataRow row = dt.NewRow();
row["ProId"] = product.ProId;
row["ProName"] = product.ProName;
row["ProPrice"] = product.ProPrice;
row["num"] = 1;
dt.Rows.Add(row);
Session["GoodsCart"] = dt;
}
else {
//判断是否存在该产品
DataTable dt = Session["GoodsCart"] as DataTable;
int idex = 0;
bool isExisterKey = false;
for (int i = 0; i < dt.Rows.Count; i++)
{
int pId =Convert.ToInt32(dt.Rows[i]["ProId"].ToString());
if(proId==pId)
{
isExisterKey = true;
idex = i;
break;
}
}
if (isExisterKey)
{
dt.Rows[idex]["num"] = (Convert.ToInt32(dt.Rows[idex]["num"].ToString()) + 1).ToString();
}
else
{
ProductInfo product = ProductManger.GetProduct(proId);
DataRow row = dt.NewRow();
row["ProId"] = product.ProId;
row["ProName"] = product.ProName;
row["ProPrice"] = product.ProPrice;
row["num"] = 1;
dt.Rows.Add(row);
}
Session["GoodsCart"] = dt;
}
Response.Redirect("~/ShoppingCart.aspx");
}
else
{
Response.Write("<script>alert('您还没有登录,请先登录再购买!');location.href='login.aspx'</script>");
}
}
}
}
ShoppingCart.aspx
<%@ Page Language="C#" CodeFile="ShoppingCart.aspx.cs" Inherits="ShoppingCart" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>购物车</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table align="center" border="0" cellpadding="0" cellspacing="0" style="font-size: 10pt;
width: 637px;">
<tr>
<td style="width: 637px;
height: 120px;background-image: url(Image/购物车/子页头.jpg);" align="left" valign="bottom">
<table border="0" cellpadding="0" cellspacing="0" style="width: 630px">
<tr>
<td align="left" style="width: 159px">
</td>
<td align="left" style="width: 319px">
<asp:Image ID="Image1" runat="server" ImageUrl="~/Image/购物车/购物车.jpg" /></td>
<td align="right" style="width: 310px">
</td>
<td style="width: 42px">
</td>
</tr>
<tr>
<td align="left" style="width: 159px; height: 17px">
</td>
<td align="left" style="width: 319px; height: 17px;">
</td>
<td align="right" style="width: 310px; height: 17px;">
<asp:LinkButton ID="lnkbtnContinue" runat="server" OnClick="lnkbtnContinue_Click" ForeColor="#FF8000">继续购物</asp:LinkButton>
<asp:LinkButton ID="lnkbtnSettleAccounts" runat="server" OnClick="lnkbtnSettleAccounts_Click" ForeColor="#FF8000">结账</asp:LinkButton>
<asp:LinkButton ID="lnkbtnClear" runat="server" OnClick="lnkbtnClear_Click" OnLoad="lnkbtnClear_Load" ForeColor="#FF8000">清空购物车</asp:LinkButton></td>
<td style="width: 42px; height: 17px">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="vertical-align: top; text-align: center; background-image: url(Image/购物车/子页中间.jpg); width: 637px; height: 341px;">
<asp:DataList ID="dlShoppingCart" runat="server"
OnItemDataBound="dlShoppingCart_ItemDataBound"
OnDeleteCommand="dlShoppingCart_DeleteCommand"
OnItemCommand="dlShoppingCart_ItemCommand" CellPadding="4" ForeColor="#333333">
<ItemTemplate>
<table style="width: 368px; font-size: 10pt;" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 88px; height: 26px;">
<asp:Label ID="labGoodName" runat="server" Text='<%# eval_r("ProName") %>'></asp:Label></td>
<td style="width: 102px; height: 26px;">
<asp:Label ID="labGoodsPrice" runat="server" Text='<%# eval_r("ProPrice") %>'></asp:Label></td>
<td style="width: 50px; height: 26px;">
<asp:TextBox ID="txtGoodsNum" runat="server" Text='<%# eval_r("num") %>' Width="33px"></asp:TextBox></td>
<td style="width: 76px; height: 26px">
<asp:LinkButton ID="lnkbtnUpdateCart" runat="server" CommandArgument='<%# eval_r("ProId") %>'
CommandName="updateNum" ForeColor="Black">更新购物车</asp:LinkButton></td>
<td style="height: 26px">
<asp:LinkButton ID="lnkbtnDel" runat="server" CommandArgument='<%# eval_r("ProId") %>'
CommandName="delete" ForeColor="Black" OnClientClick="return confirm('确定要删除吗?')">删除</asp:LinkButton></td>
</tr>
</table>
</ItemTemplate>
<SelectedItemStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderTemplate><table style="width: 368px; font-size: 10pt;" border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 88px; height: 26px;">
商品名称</td>
<td style="width: 102px; height: 26px;">
单价</td>
<td style="width: 50px; height: 26px;">
数量</td>
<td style="width: 76px; height: 26px">
</td>
<td style="height: 26px">
</td>
</tr>
</table>
</HeaderTemplate>
<FooterTemplate>
<table style="width: 368px; font-size: 10pt;" border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="left" colspan="4">
合计金额:<%=M_str_Count %>¥</td>
</tr>
</table>
</FooterTemplate>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<AlternatingItemStyle BackColor="White" ForeColor="#284775" />
<ItemStyle BackColor="#F7F6F3" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
</asp:DataList>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="更新数据" />
</td>
</tr>
<tr>
<td style="height: 140px; text-align: right; background-image: url(Image/购物车/子页底.jpg); width: 637px;">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Cart.BLL;
using Cart.Models;
using System.Collections.Generic;
using System.Text;
public partial class ShoppingCart : System.Web.UI.Page
{
public static string M_str_Count;
public float money = 0.0f;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//显示购物车中的商品信息
if (Session["UserID"] != null)
{
Bind();
}
else
{
RegisterStartupScript("", "<script>alert('请返回到登录页面登录!')</script>");
}
}
}
//绑定DataList控件
public void Bind()
{
if (Session["GoodsCart"] != null)
{
DataTable dt = Session["GoodsCart"] as DataTable;
dlShoppingCart.DataSource = dt;
dlShoppingCart.DataBind();
if (dt.Rows.Count == 0)
{
money = 0.0f;
M_str_Count = money.ToString();
}
}
}
protected void dlShoppingCart_ItemDataBound(object sender, DataListItemEventArgs e)
{
//用来实现数量文本框中只能输入数字
TextBox txtGoodsNum = (TextBox)e.Item.FindControl("txtGoodsNum");
Label lblprice = (Label)e.Item.FindControl("labGoodsPrice");
if (txtGoodsNum != null)
{
txtGoodsNum.Attributes["onkeyup"] = "value=value.replace(/[^\\d]/g,'')";
int num = Convert.ToInt32(txtGoodsNum.Text);
float price = Convert.ToSingle(lblprice.Text);
money += num * price;
M_str_Count = money.ToString();
}
}
//清空购物车
protected void lnkbtnClear_Click(object sender, EventArgs e)
{
if (Session["GoodsCart"] != null)
{
DataTable dt = Session["GoodsCart"] as DataTable;
dt.Rows.Clear(); ;
Session["GoodsCart"] = dt;
}
Bind();
}
//清空购物车时的提示信息
protected void lnkbtnClear_Load(object sender, EventArgs e)
{
lnkbtnClear.Attributes["onclick"] = "javascript:return confirm('你确定要清空购物车吗?')";
}
//继续购物
protected void lnkbtnContinue_Click(object sender, EventArgs e)
{
Response.Redirect("~/Default.aspx");
}
//删除购物车中的商品
protected void dlShoppingCart_DeleteCommand(object source, DataListCommandEventArgs e)
{
int ProId = Convert.ToInt32(e.CommandArgument.ToString());
if (Session["GoodsCart"] != null)
{
DataTable dt = Session["GoodsCart"] as DataTable;
for (int i = 0; i < dt.Rows.Count; i++)
{
int pId = Convert.ToInt32(dt.Rows[i]["ProId"].ToString());
if (ProId == pId)
{
dt.Rows[i].Delete();
break;
}
}
Session["GoodsCart"] = dt;
}
Bind();
}
//更新购物车
protected void dlShoppingCart_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "updateNum")
{
TextBox txtGoodsNum = (TextBox)e.Item.FindControl("txtGoodsNum");
int ProId = Convert.ToInt32(e.CommandArgument.ToString());
if (Session["GoodsCart"] != null)
{
DataTable dt = Session["GoodsCart"] as DataTable;
for (int i = 0; i < dt.Rows.Count; i++)
{
int pId = Convert.ToInt32(dt.Rows[i]["ProId"].ToString());
if (ProId == pId)
{
dt.Rows[i]["num"] = txtGoodsNum.Text;
break;
}
}
Session["GoodsCart"] = dt;
}
Bind();
}
}
其中在产品列表中处理数量的问题,是为了防止在购物车页面刷新的时候数量也会变化,DataTable中保存的信息,我们可以通过id读出来,然后保存到DataTable中,最后将DataTable绑定到DataList即可!