本章节主要讲解使用Session和SQL两种方式实现购物车功能。
一、资料准备
数据库:
以下三张表中SqlCart表在Session版本购物车中并没有使用到,在SQL购物车版本中需要使用。
create table MyUser --用户
(
UserId int primary key identity(1,1), --用户编号
UserAccount varchar(50) not null, --账号
UserPwd varchar(50) not null, --密码
UserMail varchar(100) not null, --邮箱
UserPhone varchar(20) not null, --电话
UserSex varchar(2) not null, --性别
)
insert into MyUser(UserAccount,UserPwd,UserMail,UserPhone,UserSex)
values('liubei','123456','liubei@qq.com','13547896547','男')
insert into MyUser(UserAccount,UserPwd,UserMail,UserPhone,UserSex)
values('guanyu','123456','guanyu@qq.com','15356875478','男')
insert into MyUser(UserAccount,UserPwd,UserMail,UserPhone,UserSex)
values('zhangfei','123456','zhangfei@qq.com','13666689874','男')
create table MyMilk --奶粉
(
MilkId int primary key identity(1,1),
MilkTitle nvarchar(100), --奶粉标题
MilkPic nvarchar(100), --奶粉图片
MilkPrice decimal(10,2), --奶粉价格
MilkWeight int --奶粉重量(克)
)
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('美素力金装','1.jpg','229','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('惠氏启赋','2.jpg','210','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('爱他美婴儿配方','3.jpg','378','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('美赞臣A+','4.jpg','350','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('美赞臣婴儿配方','5.jpg','268','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('诺优能婴儿配方','6.jpg','278','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('飞鹤星飞帆','7.jpg','209','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('合生元超级呵护','8.jpg','315','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('合生元阿尔法星','9.jpg','339','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('美素婴幼儿','10.jpg','318','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('雅培亲体金装','11.jpg','210','900')
insert into MyMilk(MilkTitle,MilkPic,MilkPrice,MilkWeight)
values('开心羊金装','12.jpg','205','900')
create table SqlCart
(
CartId int primary key identity(1,1),
UserId int,--用户编号
MilkId int,--产品编号
MilkCount int,--产品数量
)
实体类:
//会员信息
public class MyUserEntity
{
public int UserId { get; set; }
public string UserAccount { get; set; }
public string UserPwd { get; set; }
public string UserMail { get; set; }
public string UserPhone { get; set; }
public string UserSex { get; set; }
}
//商品信息
public class MyMilkEntity
{
public int MilkId { get; set; } //编号
public string MilkTitle { get; set; } //名称标题
public string MilkPic { get; set; } //图片
public double MilkPrice { get; set; } //价格
public int MilkWeight { get; set; } //重量
}
//Session版购物车
public class MyCartEntity
{
public int MilkId { get; set; } //编号
public int Count { get; set; } //商品购买数量
}
//SQL版购物车
public class SqlCartEntity
{
public int CartId{get;set;}
public int UserId{get;set;}
public int MilkId{get;set;}
public int MilkCount{get;set;}
//-----------------------------------------
public MyUserEntity MyUser { get; set; }
public MyMilkEntity MyMilk { get; set; }
}
数据访问(DBHelper参照第一章):
public class MyUserDAL
{
DBHelper db = new DBHelper();
public MyUserDAL()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
#region 用户登录
/// <summary>
/// 用户登录
/// </summary>
/// <param name="strAcc">用户名</param>
/// <param name="strPwd">密码</param>
/// <returns>布尔值,登录成功返回用户ID,登录失败返回0</returns>
public MyUserEntity Login(string strAcc, string strPwd)
{
string sql = "select * from MyUser where UserAccount = @UserAccount and UserPwd=@UserPwd";
db.PrepareSql(sql);
db.SetParameter("UserAccount", strAcc);
db.SetParameter("UserPwd", strPwd);
DataTable dt = new DataTable();
dt = db.ExecQuery();
if (dt.Rows.Count != 1)
return null;
MyUserEntity entity = new MyUserEntity();
entity.UserId = int.Parse(dt.Rows[0]["UserId"].ToString());
entity.UserAccount = dt.Rows[0]["UserAccount"].ToString();
entity.UserPwd = dt.Rows[0]["UserPwd"].ToString();
entity.UserMail = dt.Rows[0]["UserMail"].ToString();
entity.UserPhone = dt.Rows[0]["UserPhone"].ToString();
entity.UserSex = dt.Rows[0]["UserSex"].ToString();
return entity;
}
#endregion
#region 根据用户ID查询用户信息
public MyUserEntity Detail(int userId)
{
string sql = "select * from MyUser where UserId=" + userId;
db.PrepareSql(sql);
DataTable dt = new DataTable();
dt = db.ExecQuery();
if (dt.Rows.Count == 0)
return null;
MyUserEntity entity = new MyUserEntity();
entity.UserId = int.Parse(dt.Rows[0]["UserId"].ToString());
entity.UserAccount = dt.Rows[0]["UserAccount"].ToString();
entity.UserPwd = dt.Rows[0]["UserPwd"].ToString();
entity.UserMail = dt.Rows[0]["UserMail"].ToString();
entity.UserPhone = dt.Rows[0]["UserPhone"].ToString();
entity.UserSex = dt.Rows[0]["UserSex"].ToString();
return entity;
}
#endregion
}
public class MyMilkDAL
{
DBHelper db = new DBHelper();
#region 查询所有的奶粉
public List<MyMilkEntity> List()
{
string sql = "select * from MyMilk";
db.PrepareSql(sql);
DataTable dt = new DataTable();
dt = db.ExecQuery();
List<MyMilkEntity> list = new List<MyMilkEntity>();
foreach (DataRow dr in dt.Rows)
{
MyMilkEntity entity = new MyMilkEntity();
entity.MilkId = int.Parse(dr["MilkId"].ToString());
entity.MilkTitle = dr["MilkTitle"].ToString();
entity.MilkPic = dr["MilkPic"].ToString();
entity.MilkPrice = double.Parse(dr["MilkPrice"].ToString());
entity.MilkWeight = int.Parse(dr["MilkWeight"].ToString());
list.Add(entity);
}
return list;
}
#endregion
#region 查询一个奶粉的详情
public MyMilkEntity Detail(int milkId)
{
string sql = "select * from MyMilk where MilkId = " + milkId;
db.PrepareSql(sql);
DataTable dt = new DataTable();
dt = db.ExecQuery();
if (dt.Rows.Count == 0)
return null;
MyMilkEntity entity = new MyMilkEntity();
entity.MilkId = int.Parse(dt.Rows[0]["MilkId"].ToString());
entity.MilkTitle = dt.Rows[0]["MilkTitle"].ToString();
entity.MilkPic = dt.Rows[0]["MilkPic"].ToString();
entity.MilkPrice = double.Parse(dt.Rows[0]["MilkPrice"].ToString());
entity.MilkWeight = int.Parse(dt.Rows[0]["MilkWeight"].ToString());
return entity;
}
#endregion
}
public class SqlCartDAL
{
DBHelper db = new DBHelper();
#region 添加
public int Add(SqlCartEntity entity)
{
string sql = "insert into SqlCart(UserId,MilkId,MilkCount) values(@UserId,@MilkId,@MilkCount) ";
db.PrepareSql(sql);
db.SetParameter("UserId", entity.UserId);
db.SetParameter("MilkId", entity.MilkId);
db.SetParameter("MilkCount", entity.MilkCount);
return db.ExecNonQuery();
}
#endregion
#region 删除
public int Delete(int CartId)
{
string sql = "delete from SqlCart where CartId=" + CartId;
db.PrepareSql(sql);
return db.ExecNonQuery();
}
#endregion
#region 修改
public int Update(SqlCartEntity entity)
{
string sql = "update SqlCart set UserId=@UserId,MilkId=@MilkId,MilkCount=@MilkCount where CartId=@CartId";
db.PrepareSql(sql);
db.SetParameter("UserId", entity.UserId);
db.SetParameter("MilkId", entity.MilkId);
db.SetParameter("MilkCount", entity.MilkCount);
db.SetParameter("CartId", entity.CartId);
return db.ExecNonQuery();
}
#endregion
#region 查询列表
public List<SqlCartEntity> list()
{
string sql = "select * from SqlCart inner join MyMilk on SqlCart.MilkId = MyMilk.MilkId";
db.PrepareSql(sql);
DataTable dt = new DataTable();
dt = db.ExecQuery();
List<SqlCartEntity> list = new List<SqlCartEntity>();
foreach (DataRow dr in dt.Rows)
{
SqlCartEntity entity = new SqlCartEntity();
entity.CartId = int.Parse(dr["CartId"].ToString());
entity.UserId = int.Parse(dr["UserId"].ToString());
entity.MilkId = int.Parse(dr["MilkId"].ToString());
entity.MilkCount = int.Parse(dr["MilkCount"].ToString());
entity.MyMilk = new MyMilkEntity();
entity.MyMilk.MilkPic = dr["MilkPic"].ToString();
entity.MyMilk.MilkPrice = double.Parse(dr["MilkPrice"].ToString());
entity.MyMilk.MilkTitle = dr["MilkTitle"].ToString();
entity.MyMilk.MilkWeight = int.Parse(dr["MilkWeight"].ToString());
list.Add(entity);
}
return list;
}
#endregion
#region 查询详情
public SqlCartEntity Detail(int CartId)
{
string sql = "select * from SqlCart where CartId=" + CartId;
DataTable dt = new DataTable();
db.PrepareSql(sql);
dt = db.ExecQuery();
if (dt.Rows.Count == 0)
return null;
SqlCartEntity entity = new SqlCartEntity();
entity.CartId = int.Parse(dt.Rows[0]["CartId"].ToString());
entity.UserId = int.Parse(dt.Rows[0]["UserId"].ToString());
entity.MilkId = int.Parse(dt.Rows[0]["MilkId"].ToString());
entity.MilkCount = int.Parse(dt.Rows[0]["MilkCount"].ToString());
return entity;
}
#endregion
//---------------------------------------------------------------------------------------------------------
#region 搜索
public List<SqlCartEntity> Search(SqlCartEntity cartEntity)
{
string sql = "select * from SqlCart inner join MyMilk on SqlCart.MilkId = MyMilk.MilkId where 1 = 1";
if (cartEntity.UserId != 0)
sql += " and UserId = " + cartEntity.UserId;
if (cartEntity.MilkId != 0)
sql += " and SqlCart.MilkId = " + cartEntity.MilkId;
List<SqlCartEntity> list = new List<SqlCartEntity>();
db.PrepareSql(sql);
DataTable dt = new DataTable();
dt = db.ExecQuery();
foreach (DataRow dr in dt.Rows)
{
SqlCartEntity entity = new SqlCartEntity();
entity.CartId = int.Parse(dr["CartId"].ToString());
entity.UserId = int.Parse(dr["UserId"].ToString());
entity.MilkId = int.Parse(dr["MilkId"].ToString());
entity.MilkCount = int.Parse(dr["MilkCount"].ToString());
entity.MyMilk = new MyMilkEntity();
entity.MyMilk.MilkPic = dr["MilkPic"].ToString();
entity.MyMilk.MilkPrice = double.Parse(dr["MilkPrice"].ToString());
entity.MyMilk.MilkTitle = dr["MilkTitle"].ToString();
entity.MyMilk.MilkWeight = int.Parse(dr["MilkWeight"].ToString());
list.Add(entity);
}
return list;
}
#endregion
}
二、Session版购物车
此版本购物车,无需登录,游客模式可以直接将商品放入购物车。
商品列表代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session购物车</title>
<style type="text/css">
div,ul,li{ margin:0px; padding:0px;}
.milk{ width:220px; float:left; line-height:30px; text-align:center; border:solid 1px gray; margin:10px; padding:10px;}
.milk a{ text-decoration:none;}
.milkImg{ width:220px; text-align:center; clear:both;}
.milkTitle{ width:220px; text-align:center; clear:both;}
.priceAndCart{ clear:both;}
.price{ width:100px; float:left; color:Red;}
.cart{ width:100px; float:right}
.cart a{ display:block; height:30px; line-height:30px; text-decoration:none; background-color:Red; color:White;}
.hero img{ width:150px; height:200px;}
</style>
</head>
<body>
<h1>京东 <a href="Demo01_Cart.aspx">我的购物车</a></h1>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptMilk" runat="server">
<ItemTemplate>
<div class="milk">
<div class="milkImg"><a href="Demo01_01.aspx?MilkId=<%#Eval("MilkId") %>" target="_blank"><img src="img/<%#Eval("MilkPic")%>" alt="MilkPic" /></a></div>
<div class="milkTitle"><a href="Demo01_01.aspx?MilkId=<%#Eval("MilkId") %>" target="_blank"><%#Eval("MilkTitle")%></a></div>
<div class="priceAndCart">
<div class="price">价格:<%#Eval("MilkPrice")%></div>
<div class="cart"><a href="Demo01_AddCart.aspx?MilkId=<%#Eval("MilkId") %>">加入购物车</a></div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
public partial class Demo01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
#region 将数据绑定到Repeater控件
private void BindData()
{
MyMilkDAL dal = new MyMilkDAL();
List<MyMilkEntity> list = new List<MyMilkEntity>();
list = dal.List();
this.rptMilk.DataSource = list;
this.rptMilk.DataBind();
}
#endregion
}
商品详情代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session购物车</title>
<style type="text/css">
#divImg{ width:250px; float:left;}
#divBasic{ width:740px; float:left; padding:20px;}
#divBasic div{ line-height:30px;}
#cart a{ display:block; width:30px; height:30px; float:left; background-color:Gray; text-align:center;
text-decoration:none; color:White; line-height:30px;}
#cart input{ display:block; width:30px; height:24px; float:left; text-align:center;}
#cart #addCart{display:block; margin-left:20px; width:100px; height:30px; line-height:30px; text-decoration:none; background-color:Red; color:White;}
</style>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#a1").click(function () {
if (isNaN($("#count").val())) {
$("#count").val("1");
return;
}
var count = parseInt($("#count").val()) - 1;
if (count < 1)
return;
$("#count").val(count);
})
$("#a2").click(function () {
if (isNaN($("#count").val())) {
$("#count").val("1");
return;
}
var count = parseInt($("#count").val()) + 1;
$("#count").val(count);
})
$("#addCart").click(function () {
$("#form1").submit();
})
})
</script>
</head>
<body>
<form id="form1" runat="server" action="Demo01_AddCart.aspx">
<div style=" width:1100px; margin:20px auto;">
<div>
<div id="divImg"><asp:Image ID="imgMilk" runat="server" Width="250" Height="300" /></div>
<div id="divBasic">
<asp:HiddenField ID="MilkId" runat="server" />
<div>名称:<asp:Label ID="lblTitle" runat="server"></asp:Label></div>
<div>价格:<asp:Label ID="lblPrice" runat="server"></asp:Label></div>
<div>重量:<asp:Label ID="lblWeight" runat="server"></asp:Label></div>
<div id="cart">
<a id="a1" href="javascript:void(0);">-</a>
<asp:TextBox ID="count" runat="server" Text="1"></asp:TextBox>
<a id="a2" href="javascript:void(0);">+</a>
<a id="addCart" href="javascript:void(0);">加入购物车</a>
</div>
</div>
</div>
<div style=" clear:both;">
<h2>产品详情</h2>
<hr />
产品详情
</div>
</div>
</form>
</body>
</html>
public partial class Demo01_01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["MilkId"] == null || Request.QueryString["MilkId"].ToString() == string.Empty)
return;
if (!IsPostBack)
{
BindDetail();
}
}
#region 绑定产品详情
private void BindDetail()
{
int MilkId = int.Parse(Request.QueryString["MilkId"].ToString());
MyMilkDAL dal = new MyMilkDAL();
MyMilkEntity entity = new MyMilkEntity();
entity = dal.Detail(MilkId);
this.MilkId.Value = entity.MilkId.ToString();
this.imgMilk.ImageUrl = "img/" + entity.MilkPic;
this.lblTitle.Text = entity.MilkTitle;
this.lblPrice.Text = "¥:" + entity.MilkPrice.ToString();
this.lblWeight.Text = entity.MilkWeight + "克";
}
#endregion
}
添加至购物车代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session购物车</title>
<style type="text/css">
.lefttd{ width:200px;}
.centertd{ width:600px;}
.righttd{ width:300px;}
.righttd a{ display:block; width:120px; margin:5px; background-color:Red; text-decoration:none; color:White;
height:30px; line-height:30px; float:left; text-align:center;}
</style>
</head>
<body>
<h1 style=" color:Green;">商品已经成功添加至购物车</h1>
<form id="form1" runat="server">
<table width="1100" border="0">
<tr >
<td class="lefttd"><asp:Image ID="imgMilk" runat="server" /></td>
<td class="centertd">
<asp:Label ID="lblTitle" runat="server" ></asp:Label><br />
<asp:Label ID="lblInfo" runat="server" ></asp:Label><br />
</td>
<td class="righttd">
<a href="Demo01_01.aspx?MilkId=<%=Request["MilkId"] %>">查看商品详情</a>
<a href="Demo01_Cart.aspx">去购物车结算</a>
</td>
</tr>
</table>
</form>
</body>
</html>
public partial class Demo01_AddCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request["MilkId"] == null || Request["MilkId"] == string.Empty)
{
Response.Redirect("Demo01.aspx");
return;
}
if (!IsPostBack)
{
BindDetail();
SetSession();
}
}
#region 绑定产品详情
private void BindDetail()
{
int MilkId = int.Parse(Request["MilkId"].ToString());
MyMilkDAL dal = new MyMilkDAL();
MyMilkEntity entity = new MyMilkEntity();
entity = dal.Detail(MilkId);
this.imgMilk.ImageUrl = "img/" + entity.MilkPic;
this.lblTitle.Text = entity.MilkTitle;
int count = 1;
if (Request["count"] != null && Request["count"] != string.Empty)
count = int.Parse(Request["count"]);
this.lblInfo.Text = "价格:¥" + entity.MilkPrice + "//订单数量:" + count;
}
#endregion
#region 存储商品信息到Session
private void SetSession()
{
int MilkId = int.Parse(Request["MilkId"].ToString());
List<MyCartEntity> list;
if (Session["cart"] == null)
{
list = new List<MyCartEntity>();
}
else
{
list = (List<MyCartEntity>)Session["cart"];
}
int count = 1;
if (Request["count"] != null && Request["count"] != string.Empty)
count = int.Parse(Request["count"]);
//循环list,如果找到相同商品,则数量相加
bool isFindSame = false; //默认找不到相同的商品
for (int i = 0; i <= list.Count - 1; i++)
{
if (list[i].MilkId == MilkId)
{
list[i].Count += count;
isFindSame = true;
}
}
//没有找到相同商品则直接添加该商品记录
if (isFindSame == false)
{
MyCartEntity cartEntity = new MyCartEntity();
cartEntity.MilkId = MilkId;
cartEntity.Count = count;
list.Add(cartEntity);
}
Session["cart"] = list;
}
#endregion
}
我的购物车代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Session购物车</title>
<style type="text/css">
#a1,#a2{ display:block; width:30px; height:30px; float:left; background-color:Gray; text-align:center;
text-decoration:none; color:White; line-height:30px;}
#count{ display:block; width:30px; height:24px; float:left; text-align:center;}
</style>
</head>
<body>
<h1>我的购物车</h1>
<form id="form1" runat="server">
<asp:Repeater ID="rptCart" runat="server" onitemcommand="rptCart_ItemCommand">
<HeaderTemplate>
<table width="1100" border="0">
<tr style=" background-color:Gray;">
<td width="200">图片</td>
<td width="400">名称</td>
<td width="100">单价</td>
<td width="200">数量</td>
<td width="100">小计</td>
<td width="100">操作</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td width="200" style=" height:180px;"><img src="img/<%#Eval("MilkPic")%>" width="100" height="140" alt="" /></td>
<td width="400"><%#Eval("MilkTitle")%></td>
<td width="100">¥<%#Eval("MilkPrice")%></td>
<td width="200">
<asp:LinkButton ID="a1" runat="server" ClientIDMode="Static" CommandName="countdel" CommandArgument='<%#Eval("MilkId")%>'>-</asp:LinkButton>
<input type="text" value='<%#Eval("Count")%>' id="count" />
<asp:LinkButton ID="a2" runat="server" ClientIDMode="Static" CommandName="countadd" CommandArgument='<%#Eval("MilkId")%>'>+</asp:LinkButton>
</td>
<td width="100"><%#double.Parse(Eval("MilkPrice").ToString()) * double.Parse(Eval("Count").ToString())%></td>
<td width="100">
<asp:LinkButton ID="lbDel" runat="server" CommandName="del" CommandArgument='<%#Eval("MilkId")%>'>删除</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<div style=" font-size:20px; color:Red; font-weight:bold;">
<div style="width:100px; float:left; height:30px; line-height:40px; ">总计:<span id="spanSumMoney" runat="server" clientidmode="Static"></span></div>
<a href="#" style="display:block; width:120px; margin:5px; background-color:Red; text-decoration:none; color:White;
height:30px; line-height:30px; float:left; text-align:center;">去结算</a>
</div>
</form>
</body>
</html>
public partial class Demo01_Cart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["cart"] == null)
{
Response.Write("<h1>购物车中没有商品</h1>");
Response.End();
return;
}
if (!IsPostBack)
{
BindCart();
}
}
#region 绑定购物车信息到Repeater
private void BindCart()
{
//查询出购物车信息
List<MyCartEntity> listCart = new List<MyCartEntity>();
listCart = (List<MyCartEntity>)Session["cart"];
//查询出商品信息
MyMilkDAL dal = new MyMilkDAL();
List<MyMilkEntity> listMilk = new List<MyMilkEntity>();
listMilk = dal.List();
var result = from MyCartEntity cart in listCart
join MyMilkEntity milk in listMilk on cart.MilkId equals milk.MilkId
select new
{
MilkId = milk.MilkId,
MilkPic = milk.MilkPic,
MilkPrice = milk.MilkPrice,
MilkTitle = milk.MilkTitle,
Count = cart.Count
};
//绑定到数据绑定控件
this.rptCart.DataSource = result;
this.rptCart.DataBind();
//计算订单总金额
double sumMoney = 0;
foreach (var item in result)
sumMoney += item.MilkPrice * item.Count;
this.spanSumMoney.InnerHtml = sumMoney.ToString();
}
#endregion
//购物车添加数量
private void AddOne(int MilkId)
{
List<MyCartEntity> list = new List<MyCartEntity>();
list = (List<MyCartEntity>)Session["cart"];
for (int i = 0; i <= list.Count - 1; i++)
{
if (list[i].MilkId == MilkId)
{
list[i].Count++;
}
}
Session["cart"] = list;
}
//购物车减少数量
private void ReduceOne(int MilkId)
{
List<MyCartEntity> list = new List<MyCartEntity>();
list = (List<MyCartEntity>)Session["cart"];
for (int i = 0; i <= list.Count - 1; i++)
{
if (list[i].MilkId == MilkId && list[i].Count > 1)
{
if (list[i].Count <= 1)
return;
list[i].Count--;
}
}
Session["cart"] = list;
}
//购物车删除项目
private void DeleteCart(int MilkId)
{
List<MyCartEntity> list = new List<MyCartEntity>();
list = (List<MyCartEntity>)Session["cart"];
for (int i = 0; i <= list.Count - 1; i++)
{
if (list[i].MilkId == MilkId)
{
list.RemoveAt(i);
break;
}
}
Session["cart"] = list;
}
protected void rptCart_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("countadd")) // 加数量
{
this.AddOne(int.Parse(e.CommandArgument.ToString()));
}
if (e.CommandName.Equals("countdel")) //减数量
{
this.ReduceOne(int.Parse(e.CommandArgument.ToString()));
}
if (e.CommandName.Equals("del")) //删除
{
this.DeleteCart(int.Parse(e.CommandArgument.ToString()));
}
BindCart();
}
}
三、SQL版本购物车
此版本购物车,需要用户登录之后才能将商品放入购物车。
用户登录代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL购物车-用户登录</title>
<style type="text/css">
#container{ text-align:center;}
.righttd
{
width: 460px;
}
.lefted
{
width: 196px;
}
.mytitle{ font-size:18px; font-weight:bold;}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="container">
<table>
<tr>
<td align="center" height="30" class="mytitle" colspan="2">用户登录</td>
</tr>
<tr>
<td align="right" class="lefted" height="30">用户名:</td>
<td align="left" class="righttd" height="30">
<asp:TextBox ID="txtAccount" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30">密码:</td>
<td align="left" class="righttd" height="30">
<asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30"></td>
<td align="left" class="righttd" height="30">
<asp:Button ID="btLogin" runat="server" onclick="btLogin_Click" Text="登 录" />
</td>
</tr>
<tr>
<td align="right" class="lefted" height="30"></td>
<td align="left" class="righttd" height="30">
<asp:Label ID="lblErrInfo" runat="server" ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
public partial class Demo02_Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region 登录
protected void btLogin_Click(object sender, EventArgs e)
{
MyUserDAL dal = new MyUserDAL();
MyUserEntity entity = new MyUserEntity();
entity = dal.Login(this.txtAccount.Text.Trim(), this.txtPwd.Text.Trim());
if (entity != null)
{
//此处可以将用户名或这ID保存到Session,其他页面需要其他信息的时候在从数据库查询出来
//也可以将整个用户对象保存到Session中
Session["User"] = entity;
Session.Timeout = 30; //Session过期时间为30分钟
Response.Redirect("Demo02.aspx");
}
else
{
this.lblErrInfo.Text = "登录失败:用户名或密码错误!";
return;
}
}
#endregion
}
商品列表代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL版本购物车</title>
<style type="text/css">
div,ul,li{ margin:0px; padding:0px;}
.milk{ width:220px; float:left; line-height:30px; text-align:center; border:solid 1px gray; margin:10px; padding:10px;}
.milk a{ text-decoration:none;}
.milkImg{ width:220px; text-align:center; clear:both;}
.milkTitle{ width:220px; text-align:center; clear:both;}
.priceAndCart{ clear:both;}
.price{ width:100px; float:left; color:Red;}
.cart{ width:100px; float:right}
.cart a{ display:block; height:30px; line-height:30px; text-decoration:none; background-color:Red; color:White;}
.hero img{ width:150px; height:200px;}
</style>
</head>
<body>
<h1>
京东 <a href="Demo02_Cart.aspx">我的购物车</a> <a href="Demo02_Login.aspx">登录</a>
<span id="LoginUserSpan" runat="server" clientidmode="Static"></span>
</h1>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="rptMilk" runat="server">
<ItemTemplate>
<div class="milk">
<div class="milkImg"><a href="Demo02_01.aspx?MilkId=<%#Eval("MilkId") %>" target="_blank"><img src="img/<%#Eval("MilkPic")%>" alt="MilkPic" /></a></div>
<div class="milkTitle"><a href="Demo02_01.aspx?MilkId=<%#Eval("MilkId") %>" target="_blank"><%#Eval("MilkTitle")%></a></div>
<div class="priceAndCart">
<div class="price">价格:<%#Eval("MilkPrice")%></div>
<div class="cart"><a href="Demo02_AddCart.aspx?MilkId=<%#Eval("MilkId") %>">加入购物车</a></div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
public partial class Demo02 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
#region 将数据绑定到Repeater控件
private void BindData()
{
//绑定数据到Repeater
MyMilkDAL dal = new MyMilkDAL();
List<MyMilkEntity> list = new List<MyMilkEntity>();
list = dal.List();
this.rptMilk.DataSource = list;
this.rptMilk.DataBind();
//绑定数据到登录信息
if (Session["User"] != null)
{
this.LoginUserSpan.InnerHtml = "当前用户:" + ((MyUserEntity)Session["User"]).UserAccount;
}
}
#endregion
}
商品详情代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL购物车</title>
<style type="text/css">
#divImg{ width:250px; float:left;}
#divBasic{ width:740px; float:left; padding:20px;}
#divBasic div{ line-height:30px;}
#cart a{ display:block; width:30px; height:30px; float:left; background-color:Gray; text-align:center;
text-decoration:none; color:White; line-height:30px;}
#cart input{ display:block; width:30px; height:24px; float:left; text-align:center;}
#cart #addCart{display:block; margin-left:20px; width:100px; height:30px; line-height:30px; text-decoration:none; background-color:Red; color:White;}
</style>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#a1").click(function () {
if (isNaN($("#count").val())) {
$("#count").val("1");
return;
}
var count = parseInt($("#count").val()) - 1;
if (count < 1)
return;
$("#count").val(count);
})
$("#a2").click(function () {
if (isNaN($("#count").val())) {
$("#count").val("1");
return;
}
var count = parseInt($("#count").val()) + 1;
$("#count").val(count);
})
$("#addCart").click(function () {
$("#form1").submit();
})
})
</script>
</head>
<body>
<form id="form1" runat="server" action="Demo02_AddCart.aspx">
<div style=" width:1100px; margin:20px auto;">
<div>
<div id="divImg"><asp:Image ID="imgMilk" runat="server" Width="250" Height="300" /></div>
<div id="divBasic">
<asp:HiddenField ID="MilkId" runat="server" />
<div>名称:<asp:Label ID="lblTitle" runat="server"></asp:Label></div>
<div>价格:<asp:Label ID="lblPrice" runat="server"></asp:Label></div>
<div>重量:<asp:Label ID="lblWeight" runat="server"></asp:Label></div>
<div id="cart">
<a id="a1" href="javascript:void(0);">-</a>
<asp:TextBox ID="count" runat="server" Text="1"></asp:TextBox>
<a id="a2" href="javascript:void(0);">+</a>
<a id="addCart" href="javascript:void(0);">加入购物车</a>
</div>
</div>
</div>
<div style=" clear:both;">
<h2>产品详情</h2>
<hr />
产品详情
</div>
</div>
</form>
</body>
</html>
public partial class Demo02_01 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["MilkId"] == null || Request.QueryString["MilkId"].ToString() == string.Empty)
return;
if (!IsPostBack)
{
BindDetail();
}
}
#region 绑定产品详情
private void BindDetail()
{
int MilkId = int.Parse(Request.QueryString["MilkId"].ToString());
MyMilkDAL dal = new MyMilkDAL();
MyMilkEntity entity = new MyMilkEntity();
entity = dal.Detail(MilkId);
this.MilkId.Value = entity.MilkId.ToString();
this.imgMilk.ImageUrl = "img/" + entity.MilkPic;
this.lblTitle.Text = entity.MilkTitle;
this.lblPrice.Text = "¥:" + entity.MilkPrice.ToString();
this.lblWeight.Text = entity.MilkWeight + "克";
}
#endregion
}
添加至购物车代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL购物车</title>
<style type="text/css">
.lefttd{ width:200px;}
.centertd{ width:600px;}
.righttd{ width:300px;}
.righttd a{ display:block; width:120px; margin:5px; background-color:Red; text-decoration:none; color:White;
height:30px; line-height:30px; float:left; text-align:center;}
</style>
</head>
<body>
<h1 style=" color:Green;">商品已经成功添加至购物车</h1>
<form id="form1" runat="server">
<table width="1100" border="0">
<tr >
<td class="lefttd"><asp:Image ID="imgMilk" runat="server" /></td>
<td class="centertd">
<asp:Label ID="lblTitle" runat="server" ></asp:Label><br />
<asp:Label ID="lblInfo" runat="server" ></asp:Label><br />
</td>
<td class="righttd">
<a href="Demo02_01.aspx?MilkId=<%=Request["MilkId"] %>">查看商品详情</a>
<a href="Demo02_Cart.aspx">去购物车结算</a>
</td>
</tr>
</table>
</form>
</body>
</html>
public partial class Demo02_AddCart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('请先登录!');window.location.href='Demo02_Login.aspx';</script>");
return;
}
if (Request["MilkId"] == null || Request["MilkId"] == string.Empty)
{
Response.Redirect("Demo02.aspx");
return;
}
if (!IsPostBack)
{
BindDetail();
SetSql();
}
}
#region 绑定产品详情
private void BindDetail()
{
int MilkId = int.Parse(Request["MilkId"].ToString());
MyMilkDAL dal = new MyMilkDAL();
MyMilkEntity entity = new MyMilkEntity();
entity = dal.Detail(MilkId);
this.imgMilk.ImageUrl = "img/" + entity.MilkPic;
this.lblTitle.Text = entity.MilkTitle;
int count = 1;
if (Request["count"] != null && Request["count"] != string.Empty)
count = int.Parse(Request["count"]);
this.lblInfo.Text = "价格:¥" + entity.MilkPrice + "//订单数量:" + count;
}
#endregion
#region 存储购物车商品信息到数据库中
//如果需要防止页面刷新也添加购物车商品,则应该将此代码写到上个页面的添加购物车按钮上
private void SetSql()
{
int MilkId = int.Parse(Request["MilkId"].ToString());
List<SqlCartEntity> list = new List<SqlCartEntity>();
SqlCartDAL dal = new SqlCartDAL();
SqlCartEntity searchEntity = new SqlCartEntity();
searchEntity.UserId = ((MyUserEntity)Session["User"]).UserId;
searchEntity.MilkId = MilkId;
list = dal.Search(searchEntity);
//计算购物车单个商品数量
int count = 1;
if (Request["count"] != null && Request["count"] != string.Empty)
count = int.Parse(Request["count"]);
if (list.Count == 0) //如果购物车中没有商品,则添加
{
SqlCartEntity insertEntity = new SqlCartEntity();
insertEntity.UserId = ((MyUserEntity)Session["User"]).UserId;
insertEntity.MilkId = MilkId;
insertEntity.MilkCount = count;
dal.Add(insertEntity);
}
else //如果购物车中有该商品,则修改其订单数量
{
int CartId = list[0].CartId;
SqlCartEntity updateEntity = new SqlCartEntity();
updateEntity = dal.Detail(CartId);
updateEntity.MilkCount += count;
dal.Update(updateEntity);
}
}
#endregion
}
我的购物车代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>SQL购物车</title>
<style type="text/css">
#a1,#a2{ display:block; width:30px; height:30px; float:left; background-color:Gray; text-align:center;
text-decoration:none; color:White; line-height:30px;}
#count{ display:block; width:30px; height:24px; float:left; text-align:center;}
</style>
</head>
<body>
<h1>我的购物车</h1>
<form id="form1" runat="server">
<asp:Repeater ID="rptCart" runat="server" onitemcommand="rptCart_ItemCommand">
<HeaderTemplate>
<table width="1100" border="0">
<tr style=" background-color:Gray;">
<td width="200">图片</td>
<td width="400">名称</td>
<td width="100">单价</td>
<td width="200">数量</td>
<td width="100">小计</td>
<td width="100">操作</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td width="200" style=" height:180px;"><img src="img/<%#Eval("MyMilk.MilkPic")%>" width="100" height="140" alt="" /></td>
<td width="400"><%#Eval("MyMilk.MilkTitle")%></td>
<td width="100">¥<%#Eval("MyMilk.MilkPrice")%></td>
<td width="200">
<asp:LinkButton ID="a1" runat="server" ClientIDMode="Static" CommandName="countdel" CommandArgument='<%#Eval("CartId")%>'>-</asp:LinkButton>
<input type="text" value='<%#Eval("MilkCount")%>' id="count" />
<asp:LinkButton ID="a2" runat="server" ClientIDMode="Static" CommandName="countadd" CommandArgument='<%#Eval("CartId")%>'>+</asp:LinkButton>
</td>
<td width="100"><%#double.Parse(Eval("MyMilk.MilkPrice").ToString()) * double.Parse(Eval("MilkCount").ToString())%></td>
<td width="100">
<asp:LinkButton ID="lbDel" runat="server" CommandName="del" CommandArgument='<%#Eval("CartId")%>'>删除</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<div style=" font-size:20px; color:Red; font-weight:bold;">
<div style="width:100px; float:left; height:30px; line-height:40px; ">总计:<span id="spanSumMoney" runat="server" clientidmode="Static"></span></div>
<a href="#" style="display:block; width:120px; margin:5px; background-color:Red; text-decoration:none; color:White;
height:30px; line-height:30px; float:left; text-align:center;">去结算</a>
</div>
</form>
</body>
</html>
public partial class Demo02_Cart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["User"] == null)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "js", "<script>alert('请先登录!');window.location.href='Demo02_Login.aspx';</script>");
return;
}
if (!IsPostBack)
{
BindCart();
}
}
#region 绑定购物车信息到Repeater
private void BindCart()
{
List<SqlCartEntity> listCart = new List<SqlCartEntity>();
SqlCartDAL dal = new SqlCartDAL();
SqlCartEntity searchEntity = new SqlCartEntity();
searchEntity.UserId = ((MyUserEntity)Session["User"]).UserId;
listCart = dal.Search(searchEntity);
if (listCart.Count == 0)
{
Response.Write("<h1>购物车中没有商品</h1>");
Response.End();
return;
}
//绑定到数据绑定控件
this.rptCart.DataSource = listCart;
this.rptCart.DataBind();
//计算订单总金额
double sumMoney = 0;
foreach (SqlCartEntity item in listCart)
sumMoney += item.MyMilk.MilkPrice * item.MilkCount;
this.spanSumMoney.InnerHtml = sumMoney.ToString();
}
#endregion
//购物车添加数量
private void AddOne(int CartId)
{
SqlCartDAL dal = new SqlCartDAL();
SqlCartEntity entity = new SqlCartEntity();
entity = dal.Detail(CartId);
entity.MilkCount += 1;
dal.Update(entity);
}
//购物车减少数量
private void ReduceOne(int CartId)
{
SqlCartDAL dal = new SqlCartDAL();
SqlCartEntity entity = new SqlCartEntity();
entity = dal.Detail(CartId);
if (entity.MilkCount <= 1)
return;
entity.MilkCount -= 1;
dal.Update(entity);
}
//购物车删除项目
private void DeleteCart(int CartId)
{
SqlCartDAL dal = new SqlCartDAL();
dal.Delete(CartId);
}
protected void rptCart_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName.Equals("countadd")) // 加数量
{
this.AddOne(int.Parse(e.CommandArgument.ToString()));
}
if (e.CommandName.Equals("countdel")) //减数量
{
this.ReduceOne(int.Parse(e.CommandArgument.ToString()));
}
if (e.CommandName.Equals("del")) //删除
{
this.DeleteCart(int.Parse(e.CommandArgument.ToString()));
}
BindCart();
}
}