Profile购物车的实现完整代码!AJAX添加或删除产品,购物车价格变动

孤者浪人 提交于 2020-03-11 16:07:47

前台代码

 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ShoppingCartControl.ascx.cs" Inherits="UControl_ShoppingCartControl" %>
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI" TagPrefix="asp" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<script type="text/javascript">
    function show(productID) {
        if (confirm("确实要删除吗?")) {
            url = "ShoppingCart.aspx?DeleteItem=" + productID;
            document.location.href = url;
        }
    }
    </script>
<style type="text/css">

.good_them_tit{
background:url('../img/bg_tag_1.gif') repeat-x left bottom;
height:27px;
line-height:27px;
padding:0 10px;
text-align:left;
font-size:14px;
color:#222;
position:relative;
}
  h1,h2,h3,h4,h5,h6{
font-size:12px;
}
h1,h2,h3,h4,h5,h6,ul,li,dl,dt,dd,form,img,p{
margin:0 auto;
padding:0;
border:none;
list-style-type:none;
}

a:link {
color: #666;
text-decoration:none;
}
.market{
text-decoration:line-through;
}
.promote_price{
color:#ff6600;
font-weight:bold;
font-size:15px;
font-family:Verdana;
}
.inputborder{
border:1px solid #ccc;
}

.fred{
color:#ff0000;
}
.bnt_number6{
width:103px;
background:url('../img/bg.gif') no-repeat -257px -31px;
    }
.bnt_number2,.bnt_number4,.bnt_number6,.bnt_number8,.bnt_number10{
border:none;
height:22px;
text-align:center;
color:#fff;
cursor:pointer;
}
</style>
<h3 class="good_them_tit">
    商品列表</h3>
<div style="text-align:center">
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
   
  
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<HeaderTemplate>
    <table bgcolor="#dddddd" border="0" cellpadding="5"
    cellspacing="1" width="100%">
    <tr>
        <th bgcolor="#ffffff">
            商品名称</th>
       <th bgcolor="#ffffff">
            市场价</th>
        <th bgcolor="#ffffff">
            本店价</th>
        <th bgcolor="#ffffff">
            购买数量</th>
        <th bgcolor="#ffffff">
            小计</th>
<%--        <th bgcolor="#ffffff">
            操作</th>--%>
    </tr>     
</HeaderTemplate>
<ItemTemplate>
    <tr>
        <td align="center" bgcolor="#ffffff" style="width:20%">
            <a href='../View/ProductDetail.aspx?ProductID=<%#Eval("ID") %>' target="_blank">
              <img src='../images/<%#Eval("ImgUrl")%>' width="140px" height="150px" border="0"></a><br />
            <a href='../View/ProductDetail.aspx?ProductID=<%#Eval("ID") %>'target="_blank"><%#Eval("Name") %></a>
        </td>
        <td align="center" bgcolor="#ffffff" class="market" style="width:10%">
            <%#string.Format("{0:c}",Eval("Price")) %>
            </td>
        <td align="center" bgcolor="#ffffff" class="promote_price" style="width:10%">
            <%#string.Format("{0:c}",Eval("MemberPrice")) %>
            </td>
        <td align="center" bgcolor="#ffffff" style="width:10%">
            <table width="100%">
                <tr>
                    <td style="width:20%">
                        <asp:ImageButton ID="ImageButton1" CommandArgument='<%#Eval("ID") %>' CommandName="ReduceQuantity" runat="server" ImageUrl="../Manage/images/qmimages/symbol_2.gif" />
                    </td>
                    <td style="width:60%">
                    <asp:TextBox ID="txtQuantity" runat="server" Width="50px" Text='<%#Eval("Quantity") %>'></asp:TextBox>
                    </td>
                    <td style="width:20%">
                        <asp:ImageButton ID="ImageButton2" CommandArgument='<%#Eval("ID") %>' CommandName="AddQuantity" runat="server" ImageUrl="../Manage/images/qmimages/symbol_1.gif" />
                    </td>
                </tr>
              
            </table>
        </td>
        <td align="center" bgcolor="#ffffff" class="promote_price" style="width:10%">
            <asp:Literal ID="LtSubTotal" runat="server" Text='<%#string.Format("{0:c}",Eval("SubTotal")) %>'></asp:Literal>
            </td>
<%--        <td align="center" bgcolor="#ffffff" style="width:10%">
              <a href='javascript:show(<%#Eval("ID") %>)'>删除</a>
        </td>--%>
    </tr>
</ItemTemplate>
<FooterTemplate>

    </table>
</FooterTemplate>
</asp:Repeater>
        <asp:Literal ID="LtCartStatus" runat="server" Visible="false"></asp:Literal>
<table width="100%">
<tr>
    <td colspan="4" align="right">
      <font color="red">  总金额为:<asp:Literal ID="LtTotal" runat="server"></asp:Literal></font>
    </td>
</tr>
</table>
 </ContentTemplate>
    </asp:UpdatePanel>
<table align="center" border="0" cellpadding="5" cellspacing="0" width="99%">
    <tr>
        <td align="center">
            <a href="Default.aspx">
            <img alt="continue" src="../img/bg_btn_gotobuy.gif" /></a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="../Users/Checkout.aspx">
            <img alt="checkout" src="../img/bg_btn_gotocheck.gif"/></a>
            </td>
    </tr>
</table>

</div>

 

 

后台代码

 

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UControl_ShoppingCartControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindCart();
            LtTotal.Text = Profile.ShoppingCart.Total.ToString() + "元";
        }
    }

    private void BindCart()
    {
        if (Profile.ShoppingCart.CartItems.Rows.Count > 0)
        {
            Repeater1.DataSource = Profile.ShoppingCart.CartItems;
            Repeater1.DataBind();
        }
        else
        {
            LtCartStatus.Visible = true;
            LtCartStatus.Text = "您的购物车还没有商品";
        }
        //LtTotal.Text = string.Format("{0;c}", Profile.ShoppingCart.Total.ToString());
    }

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "ReduceQuantity")
        {
            Profile.ShoppingCart.RemoveItem(Convert.ToInt32(e.CommandArgument));
            BindCart();
            LtTotal.Text = Profile.ShoppingCart.Total.ToString() + "元";
        }
        if (e.CommandName == "AddQuantity")
        {
            int RecordCount = 0;
            DataTable dt = MyCompany.Factory.BLLAccess.CreateProduct().GetTabletByCondition("Product", "*", "ProductID desc", 1, 1, out RecordCount, " ProductID=" + Convert.ToInt32(e.CommandArgument) + "");
            Profile.ShoppingCart.AddItem(Convert.ToInt32(e.CommandArgument), dt.Rows[0]["Title"].ToString(), Convert.ToDecimal(dt.Rows[0]["Price"]), Convert.ToDecimal(dt.Rows[0]["MemberPrice"]), dt.Rows[0]["Image"].ToString().Substring(0, dt.Rows[0]["Image"].ToString().IndexOf("|")) + ".jpg");
            Profile.Save();
            BindCart();
            LtTotal.Text = Profile.ShoppingCart.Total.ToString()+"元";
        }
    }
}

 

 

 

BLL层购物车代码

 

using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;


namespace MyCompany.BLL
{
    /// <summary>
    ///ShopingCart 的摘要说明
    /// </summary>
    ///
    [Serializable]
    public class ShoppingCart
    {


        DataTable _CartItems = new DataTable("CartItems");

 

        public ShoppingCart()
        {

            CreatTable();

        }

        // 返回购物车中所有的商品

        public DataTable CartItems
        {

            get { return _CartItems; }

        }

        // 计算购物车中所有商品的总价钱

        public decimal Total
        {

            get
            {

                decimal sum = 0;

 

                foreach (DataRow row in _CartItems.Rows)

                    sum += Convert.ToDecimal(row["MemberPrice"].ToString()) * Convert.ToDecimal(row["Quantity"].ToString());

                return sum;

            }

        }

        // 添加商品到购物车

        public void AddItem(int ID, string Name, decimal Price,decimal MemberPrice,string ImgUrl)
        {

            if (_CartItems.Select("ID=" + ID).Length == 0)
            {

                DataRow row = _CartItems.NewRow();

                row["ID"] = ID;

                row["Name"] = Name;

                row["Price"] = Price;

                row["MemberPrice"] = MemberPrice;

                row["Quantity"] = 1;

                row["ImgUrl"] = ImgUrl;

                row["SubTotal"] = MemberPrice;

                _CartItems.Rows.Add(row);

            }

            else
            {

                foreach (DataRow row in _CartItems.Select("ID=" + ID))
                {

                    row["Quantity"] = Convert.ToDecimal(row["Quantity"].ToString()) + 1;
                    row["SubTotal"] = MemberPrice * Convert.ToDecimal(row["Quantity"]);
                }

            }

        }

        // 移除购物车中的商品

        public void RemoveItem(int ID)
        {

            if (_CartItems.Select("ID=" + ID).Length == 0)
            {

                return;

            }

            else
            {

                foreach (DataRow row in _CartItems.Select("ID=" + ID))
                {

                    row["Quantity"] = Convert.ToDecimal(row["Quantity"].ToString()) - 1;

                    row["SubTotal"] = Convert.ToDecimal(row["MemberPrice"]) * Convert.ToDecimal(row["Quantity"]);

                    if (Convert.ToDecimal(row["Quantity"].ToString()) == 0)
                    {

                        _CartItems.Rows.Remove(row);

                    }

                }

            }

        }

        // 创建DataTable

        private void CreatTable()
        {

            _CartItems.Columns.Add("ID", typeof(int));

            _CartItems.Columns.Add("Name", typeof(string));

            _CartItems.Columns.Add("Price", typeof(decimal));

            _CartItems.Columns.Add("MemberPrice", typeof(decimal));

            _CartItems.Columns.Add("Quantity", typeof(decimal));

            _CartItems.Columns.Add("ImgUrl", typeof(string));

            _CartItems.Columns.Add("SubTotal", typeof(decimal));

        }

    }
}

 

 

web.config 必须加上这句话

<anonymousIdentification enabled="true" />
  <profile>
   <properties>
    <add name="ShoppingCart" type="MyCompany.BLL.ShoppingCart" allowAnonymous="true" serializeAs="Binary"/>
      </properties>
  </profile>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!