购物网第四阶段总结笔记1:购物车页面

时间:2021-10-09 21:52:18

购物车页面是整个购物网的核心,流程如下:

商品内容页(pro.aspx)点击立即购买===》把商品加入到购物车中===》弹出一个选择框,选择是到购物车页面还是继续购物===》若是选择进入购物车页面===》进入我的购物车页面(shopcart.aspx),点击去收银台===》修改订单页面(order_modify.aspx)===》确认订单页面(order_confirm.aspx)===》订单确认成功页面(order_ok.aspx)


【一】:建立订单表和订单明细表数据表

shop_order(订单表): 

id,createdate,orderbh(订单号),

username(用户名),recname(收货人姓名),postcode,addreass,phone,email,

sendtype(送货方式),paytype(付款方式),

fp(是否要发票:0:不要发票  1:要发票),remark(说明),sendmoney(运费),detailsmoney(订单商品金额),isdel,state

购物网第四阶段总结笔记1:购物车页面


shop_orderdetails(订单明细表): id,createdate,orderid(Shop_order的外键),proid(商品id),price(商品价格),quantity(商品数量).

购物网第四阶段总结笔记1:购物车页面


然后使用动软代码生成器生成代码,复制到项目中。


【二】:自己手工写购物车类:

购物车就是一个二维表,临时存储商品的简单明细:

如:

购物车:

         商品1    :   单价   数量

         商品2    :   单价   数量

         商品3    :   单价   数量


分析,可以看出,需要建立两个类:购物车类 和购物车项类

(1):在Model层建立ShopItem.cs购物车项类,添加变量,并重构,封装字段

购物网第四阶段总结笔记1:购物车页面


购物网第四阶段总结笔记1:购物车页面


购物网第四阶段总结笔记1:购物车页面

最后的cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
/// <summary>
/// 购物车中的每一项
/// </summary>
public class ShopItem
{
private int _proid;//商品ID

public int Proid
{
get { return _proid; }
set { _proid = value; }
}
private decimal _price;//单价

public decimal Price
{
get { return _price; }
set { _price = value; }
}
private int _quantity;//商品数量

public int Quantity
{
get { return _quantity; }
set { _quantity = value; }
}
}
}


(2)向Model中添加,购物车类ShopCart.cs:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;




namespace Model
{
    /// <summary>
    /// 购物车类
    /// </summary>
    public class ShopCart
    {
        private Hashtable _sc = new Hashtable();//把购物车的集合放在Hashtable中,通过键值对来存放


        /// <summary>
        /// 想购物车中添加一种商品
        /// </summary>
        /// <param name="proid"></param>
        /// <param name="item"></param>
        public void Add(int proid, ShopItem item)
        {
            if (_sc[proid] == null)//商品id作为Hashtable的键来存储
            {
                //购物车中不存在该商品,则直接添加到购物车
                _sc.Add(proid,item);
            }
            else
            {
                //已存在该商品,先取出购物车中商品取出来,然后加1
                ShopItem si = _sc[proid] as ShopItem;//取出购物车商品
                si.Quantity += 1;//把取出的商品加1
                _sc[proid] = si;//然后再放回去
            }
        }


        /// <summary>
        /// 删除购物车中的商品
        /// </summary>
        /// <param name="proid"></param>
        public void Del(int proid)
        {
            if (_sc[proid] != null)
            {
               
               _sc.Remove(proid);
            }
            
        }




        /// <summary>
        /// 修改购物车商品的数量
        /// </summary>
        /// <param name="proid"></param>
        /// <param name="quentity"></param>
        public void Mod(int proid, int quentity)
        {
            if (_sc[proid]!=null)
            {
                if (quentity>0)//如果商品的修改目标数量大于0
                {
                     ShopItem si = _sc[proid] as ShopItem;
                si.Quantity = quentity;
                _sc[proid] = si;
                }
                else
                {
                    _sc.Remove(proid);
                }
            }
        }


        /// <summary>
        /// 获取购物车中商品种类的数量
        /// </summary>
        /// <returns></returns>
        public int GetItemCount()
        {
            return _sc.Count;//键值的数量就是商品种类的数量
        }


        /// <summary>
        /// 获取购物车中商品的总数量
        /// </summary>
        /// <returns></returns>
        public int GetItemTotalCount()
        {
            int total = 0;


            foreach (ShopItem item in _sc.Values)
            {
                total += item.Quantity;
            }
            return total;
        }


        /// <summary>
        /// 获取购物车中商品的总价
        /// </summary>
        /// <returns></returns>
        public decimal GetTotlePrice()
        {
            decimal total=0;
            foreach (ShopItem item in _sc.Values)
            {
                total += item.Price * item.Quantity;
            }
            return total;
        }


        /// <summary>
        /// 获取购物车中项的集合,用于绑定数据控件
        /// </summary>
        /// <returns></returns>
        public ICollection GetItemList()
        {
            return _sc.Values;
        }
    }
}


购物按钮的制作:在newpro.aspx页面中,点击购买,把购买的商品加入到购物车:

aspx代码:

<asp:LinkButton ID="LinkButton2" OnClick="Buy"  CommandArgument='<%#Eval("id") %>' runat="server">
<img src="images/gm.gif" />
</asp:LinkButton>

cs代码:

        //加入购物车
protected void Buy(object sender, EventArgs e)
{
/*
* 1、必须是登陆的用户才能购买
* 2、如果用户是VIP用户,则是以VIP价格来计算
* 3、产品购买的默认数量是1
*/

if (!User.Identity.IsAuthenticated)//是否是验证用户,即是否是登陆用户
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", "<script>alert('请登陆才能购买商品!')</script>");
return;
}
string proid = (sender as LinkButton).CommandArgument;
MyShop.Model.Product pro = new MyShop.DAL.ProductDAO().GetModel(int.Parse(proid));//取出商品
MyShop.Model.User user = new MyShop.DAL.UserDAO().GetModel(User.Identity.Name);//取出用户名

if (pro!=null&&user!=null)//如果商品和用户都存在
{
decimal price = 0;
if (user.type=="vip")//如果用户是vip
{
price = pro.vipprice;
}
else
{
price = pro.memberprice;
}



if (Session["shopcart"] == null)//如果Session["shopcart"]不存在
{
Session["shopcart"] = new Model.ShopCart();//新建一个Session["shopcart"]
}
Model.ShopCart sc = Session["shopcart"] as Model.ShopCart;//根据Session["shopcart"]取出Model
sc.Add(int.Parse(proid), new Model.ShopItem()
{
Quantity = 1,
Proid = int.Parse(proid),
Price = price
});

Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", "<script>if(confirm('商品添加成功,是否跳转到购物车页面')){location.href='shopcart.aspx'}else{location.href='"+Request.Url.ToString()+"'}</script>");
}
}

【三】:购物车页面的制作

(1):在首页头部显示购物车中已有的商品种类数量:

购物网第四阶段总结笔记1:购物车页面

修改母版页

aspx代码:

  <asp:HyperLink ID="htGWC" NavigateUrl="~/shopcart.aspx" runat="server">购物车</asp:HyperLink> 
cs代码:

         if (!IsPostBack)
{
if (Session["shopcart"] != null)
{
Model.ShopCart sc = Session["shopcart"] as Model.ShopCart;
if (sc.GetItemCount()>0)
{
hlGWC.Text = "购物车[<span style='font-weight:bold;color:red;'>"+sc.GetItemCount()+"</span>]";
}
}
}


(2):购物车页面的制作


aspx代码:

(1):用一个隐藏域,把商品id取出来。

<asp:HiddenField ID="hfporid" Value='<%#Eval("proid") %>' runat="server" />

 <%-- 隐藏域 --%>
<asp:HiddenField ID="hidXJ" Value='<%#Eval("price") %>' runat="server" />


                <table width="98%" border="0" align="center" cellpadding="0" cellspacing="1">
<tbody>
<tr>
<td height="1" bgcolor="cccccc">
<img src="images/dot_03.gif" width="9" height="1" border="0">
</td>
</tr>
<tr>
<td height="25" bgcolor="efefef">
<strong>  <img src="images/dot_03.gif" width="9" height="9" border="0">
</strong><b>我的购物车</b>
</td>
</tr>
<tr>
<td height="1" bgcolor="cccccc">
<img src="images/dot_03.gif" width="9" height="1" border="0">
</td>
</tr>
</tbody>
</table>
<br />
<table width="96%" border="1" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tbody>
<tr bgcolor="f1f1f1">
<td width="223" height="22">
<div align="center">
商品名称</div>
</td>
<td width="99" height="22">
<div align="center">
会员价
</div>
</td>
<td width="49" height="22">
<div align="center">
VIP价</div>
</td>
<td width="49" height="22">
<div align="center">
现价</div>
</td>
<td width="83" height="22">
<div align="center">
数量</div>
</td>
<td width="77" height="22">
<div align="center">
总价</div>
</td>
<td width="24" height="22">
<div align="center">
删</div>
</td>
</tr>
<asp:Repeater ID="repShopcart" runat="server" OnItemDataBound="repShopcart_ItemDataBound">
<ItemTemplate>
<tr bgcolor="#FFFFFF">
<td width="223" height="22" bgcolor="#FFFFFF" style="padding-left: 5px">
<div align="left">
<asp:HyperLink ID="hlproname" runat="server">HyperLink</asp:HyperLink>
<%-- 隐藏域 --%>
<asp:HiddenField ID="hfproid" Value='<%#Eval("proid") %>' runat="server" />
</div>
</td>
<td width="99" height="22" bgcolor="#FFFFFF">
<div align="center">
<asp:Literal ID="litmemberprice" runat="server"></asp:Literal>
元</div>
</td>
<td width="49" height="22" bgcolor="#FFFFFF">
<div align="center">
<asp:Literal ID="litvipprice" runat="server"></asp:Literal>
</div>
</td>
<td width="49" height="22" bgcolor="#FFFFFF">
<div align="center">

<asp:Literal ID="litXJ" Text='<%#Eval("price","{0:c2}") %>' runat="server"></asp:Literal>
<%-- 隐藏域 --%>
<asp:HiddenField ID="hidXJ" Value='<%#Eval("price") %>' runat="server" />

</div>
</td>
<td width="83" height="22" bgcolor="#FFFFFF">
<div align="center">
<font color="#dd6600">
<asp:TextBox ID="txtquantity" class="wenbenkuang" Text='<%#Eval("quantity") %>' runat="server" Width="60" OnTextChanged="Mod" AutoPostBack="true" ToolTip='<%#Eval("proid") %>'></asp:TextBox>
</font>
</div>
</td>
<td width="77" height="22" bgcolor="#FFFFFF">
<div align="center">
<font color="#FF3300">
<asp:Literal ID="littotal" runat="server"></asp:Literal></font></div>
</td>
<td width="24" height="22">
<div align="center">
<asp:LinkButton ID="lbtnDel" OnClick="Del" CommandArgument='<%#Eval("proid") %>' OnClientClick="return confirm('是否删除该商品?')" runat="server">
<img src="images/trash.gif" width="15" height="17" border="0">
</asp:LinkButton>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
<tr bgcolor="#FFFFFF">
<td height="30" colspan="7" bgcolor="#FFFFFF">
<div align="center">
<input name="Submit32" type="button" class="go-wenbenkuang" value="返回继续购物" onclick="javascript:location.href='newpro.aspx'">

<asp:Button ID="btnClear" runat="server" Text="清空购物车" onclick="btnClear_Click" />

<asp:Button ID="btnGoBuy" class="go-wenbenkuang" runat="server" Text="去收银台"
onclick="btnGoBuy_Click" />
</div>
</td>
</tr>
<tr bgcolor="#FFFFFF">
<td height="36" colspan="7" bgcolor="#FFFFFF">
<div align="center">
购物车里有商品:<asp:Literal ID="litcount" runat="server"></asp:Literal>件

总数:<asp:Literal
ID="litallcount" runat="server"></asp:Literal>件
共计:<asp:Literal ID="litsumprice" runat="server"></asp:Literal>元 您有预存款:元
</div>
</td>
</tr>
</tbody>
</table>

cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web
{
public partial class shopcart : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["shopcart"] == null)//如果Session["shopcart"]不存在
{
Session["shopcart"] = new Model.ShopCart();
}
Model.ShopCart sc = Session["shopcart"] as Model.ShopCart;
repShopcart.DataSource=sc.GetItemList();
repShopcart.DataBind();

litcount.Text = sc.GetItemCount().ToString();
litallcount.Text = sc.GetItemTotalCount().ToString();
litsumprice.Text = sc.GetTotlePrice().ToString("c2");
}
}
//绑定数据信息
protected void repShopcart_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType==ListItemType.AlternatingItem||e.Item.ItemType==ListItemType.Item)
{
string proid = (e.Item.FindControl("hfproid") as HiddenField).Value;
MyShop.Model.Product pro = new MyShop.DAL.ProductDAO().GetModel(int.Parse(proid));
if (pro!=null)
{
HyperLink hlproname = e.Item.FindControl("hlproname") as HyperLink;
Literal litmemberprice = e.Item.FindControl("litmemberprice") as Literal;
Literal litvipprice = e.Item.FindControl("litvipprice") as Literal;
HiddenField hidXJ = e.Item.FindControl("hidXJ") as HiddenField;//现价
Literal littotal = e.Item.FindControl("littotal") as Literal;
TextBox txtquantity = e.Item.FindControl("txtquantity") as TextBox;


hlproname.Text = pro.proname;
hlproname.NavigateUrl = "../pro.aspx?id="+pro.id;
hlproname.Target = "_blank";

litmemberprice.Text = pro.marketprice.ToString("c2");
litvipprice.Text = pro.vipprice.ToString("c2");


littotal.Text = (decimal.Parse(hidXJ.Value) * int.Parse(txtquantity.Text)).ToString("c2");

}
}
}

//删除商品
protected void Del(object sender, EventArgs e)
{
string proid = (sender as LinkButton).CommandArgument;
if (Session["shopcart"]!=null)
{
Model.ShopCart sc = Session["shopcart"] as Model.ShopCart;
sc.Del(int.Parse(proid));
Session["shopcart"] = sc;
}
Response.Redirect(Request.Url.ToString());
}

//修改商品数量
protected void Mod(object sender, EventArgs e)
{
TextBox txt=(sender as TextBox);
string proid = txt.ToolTip;
string quantity = txt.Text;
int x;
if (!int.TryParse(quantity,out x))
{
x = 1;
}
if (Session["shopcart"]!=null)
{
Model.ShopCart sc = Session["shopcart"] as Model.ShopCart;
sc.Mod(int.Parse(proid),x);
Session["shopcart"] = sc;
}
Response.Redirect(Request.Url.ToString());
}

//清空购物车
protected void btnClear_Click(object sender, EventArgs e)
{
Session["shopcart"] = null;
Response.Redirect(Request.Url.ToString());
}

//去收银台
protected void btnGoBuy_Click(object sender, EventArgs e)
{
if (Session["shopcart"]==null)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", "<script>alert('购物车为空,请选择要购买的商品再结账!')</script>");
return;
}
else
{
Model.ShopCart sc = Session["shopcart"] as Model.ShopCart;
if (sc.GetItemCount()==0)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "MsgBox", "<script>alert('购物车为空,请选择要购买的商品再结账!')</script>");
return;
}
}
Response.Redirect("order_modify.aspx");

}
}
}