zoukankan      html  css  js  c++  java
  • 用 序列化,反序列化的购物车

          我是新手,这是我的第一个项目,开始做购物车也做的我头疼,后面还是慢慢搞出来了,代码也更新过两次,但是还是比较乱,也没办法,将就点慢慢来,
      这只是我的一个参考, 其他的新手看了这个应该会有更好的解决办法了,

        购物车操作类

        [Serializable]
        public class CartInfo
        {
            private IDBProductManager idbpro = ProductSystemFacade.GetFacade().GetIDBProductManager();
            private string procKey="";     //下定单的商品ID,数量参数值
            IList<Product> list = null;

            #region 购物车信息抛出的属性

            /// <summary>
            /// 购物车中所有商品原总邮费
            /// </summary>
            public int TotalOldPostMoney
            {
                get
                {
                    int sum = 0;

                    list = GetNewCartItems();
                    foreach (Product item in list)
                    {
                        int proID = item.Id;
                        Product product = idbpro.Read(proID);
                        sum += product.ProPost1 * item.ProNumber;
                    }
                    return sum;
                }
            }


            /// <summary>
            /// 购物中所有商品原来的价格合计
            /// </summary>
            public decimal TotalPrice
            {
                get
                {
                    decimal sum = 0;

                    list = GetNewCartItems();
                    foreach (Product item in list)
                    {
                        int proID = item.Id;
                        Product product = idbpro.Read(proID);
                        sum += ((product.ProPrice + product.ProPost1) * item.ProNumber);
                    }
                    return sum;
                }
            }

            /// <summary>
            /// 购物车所有商品打折后的价格总计
            /// </summary>
            public decimal TotalNewPrice
            {
                get
                {
                    decimal sum = 0;

                    list = GetNewCartItems();
                    foreach (Product item in list)
                    {
                        int proID = item.Id;
                        Product pro = idbpro.Read(proID);
                        sum += ((pro.ProPrice * pro.ProSpecialOffer + pro.ProPost1) * item.ProNumber);
                    }
                    return sum;
                }
            }

            /// <summary>
            /// 返回购物车里所有商品的数量
            /// </summary>
            public int TotalNum
            {
                get
                {
                    int sum = 0;

                    list = GetNewCartItems();
                    foreach (Product item in list)
                    {
                        sum += item.ProNumber;
                    }
                    return sum;
                }
            }

            /// <summary>
            /// 下定单传的ID,数量参数
            /// </summary>
            public string ProcKey
            {
                get
                {
                    procKey = "";

                    list = GetNewCartItems();
                    foreach (Product item in list)
                    {
                        int proID = item.Id;
                        int proNum = item.ProNumber;
                        procKey += proID.ToString() + "|" + proNum.ToString() + ",";
                    }
                    return procKey;
                }
            }

            //设置获取Cookie值
            private string CookieMsg
            {
                get
                {
                    if (HttpContext.Current.Request.Cookies == null) return null;
                    if (HttpContext.Current.Request.Cookies["cart"] == null) return null;
                    return HttpContext.Current.Request.Cookies["cart"].Value;
                }
                set
                {
                    if (HttpContext.Current.Response.Cookies == null)
                    {
                        HttpCookie cookie = new HttpCookie("cart");
                        cookie.Expires = DateTime.Now.AddHours(24);   //保存序列化信息
                        HttpContext.Current.Response.Cookies.Set(cookie);
                    }
                    else
                    {
                        HttpContext.Current.Response.Cookies["cart"].Values.Clear();
                        HttpContext.Current.Response.Cookies["cart"].Value = value;
                        HttpContext.Current.Response.Cookies["cart"].Expires = DateTime.Now.AddHours(24);   //保存序列化信息
                    }
                }
            }

            #endregion

            #region 购物车的执行方法

            /// <summary>
            /// 添加商品
            /// </summary>
            /// <param name="proID">商品ID</param>
            public void AddItem(int proID)
            {
                list = GetNewCartItems();
                if (list.Count == 0)
                {
                    list.Add(new Product(proID, 1));
                }
                else
                {
                    bool b = false;
                    foreach (Product pro in list)
                    {
                        if (pro.Id == proID)
                        {
                            pro.ProNumber++;
                            b = true;
                            break;
                        }
                    }
                    if (b == false)
                    {
                        list.Add(new Product(proID, 1));
                    }
                }
                SerializeObj(list);        //序列化
            }

            /// <summary>
            /// 从购物车里移除某商品
            /// </summary>
            /// <param name="proID">商品ID</param>
            public void RemoveItem(int proID)
            {
                list = GetNewCartItems();

                for (int i = 0; i < list.Count; i++)
                {
                    Product pro = (Product)list[i];
                    if (pro.Id == proID)
                    {
                        list.RemoveAt(i);
                    }
                }
                SerializeObj(list);        //序列化
            }

            /// <summary>
            /// 修改购物车里某商品的数量
            /// </summary>
            /// <param name="ID">商品ID</param>
            /// <param name="Quantity">商品数量</param>
            public void UpdateItem(int proID, int Quantity)
            {
                bool b = false;

                list = GetNewCartItems();
                for (int i = 0; i < list.Count; i++)
                {
                    Product item = (Product)list[i];
                    if (proID == item.Id)
                    {
                        if (Quantity != item.ProNumber)
                        {
                            item.ProNumber = Quantity;
                            b = true;
                            break;
                        }
                    }
                }
                if (b == false) return;
                SerializeObj(list);        //序列化
            }

            /// <summary>
            /// 清空购物车
            /// </summary>
            public void ClearCart()
            {
                list = GetNewCartItems();

                list.Clear();
                SerializeObj(list);        //序列化  (5.12的随笔里有方法)
            }

            /// <summary>
            /// 重新序列化购物车信息
            /// </summary>
            /// <param name="cart"></param>
            public void SerializeObj(IList<Product> list)
            {
                string strCart = SerializeMsg.SerializeObject(list);        //序列化购物车信息对象
                CookieMsg = strCart;
            }
           
            /// <summary>
            /// 获取最新购物车记录
            /// </summary>
            /// <returns></returns>
            public IList<Product> GetNewCartItems()
            {
                string newMsg = CookieMsg;
                if (string.IsNullOrEmpty(newMsg))
                {
                    return new List<Product>();
                }
                object obj = SerializeMsg.DeserializeObject(newMsg);     //反序列化购物车信息

                return (IList<Product>)obj;
            }

            /// <summary>
            /// 购物车商品信息的Ilist集合
            /// </summary>
            /// <param name="cartInfo"></param>
            /// <returns></returns>
            public IList<Product> GetShoppingCartList()
            {
                IList<Product> newList = new List<Product>();
                foreach (Product item in GetNewCartItems())
                {
                    int proID = item.Id;
                    int proNum = item.ProNumber;

                    Product pro = idbpro.Read(proID);
                    pro.ProNumber = proNum;
                    newList.Add(pro);
                }
                return newList;
            }
           
            #endregion



    购物车页面源代码
       在源代码里 我把常用的DataBinder.Eval(也可以简写Eval), 用 ((Product)Container.DataItem).属性名 来代替, 有效 的提高了绑定效率. 

    <%@ Import Namespace="Plugins.ProductSystem.Domain" %>

     <div class="content-wrapper">
            <div class="top-tips">您已经选购以下商品</div><!-- end top-nav -->
      <div class="shopping-content">
      <table width="100%" border="0" cellspacing="0" cellpadding="0" class="shopping-list">
        <tr align="center" style="background:#eee">
            <td width="50%">商品名称</td>
            <td width="10%">市场价</td>
            <td width="15%">现价&nbsp;/&nbsp;单个商品运费</td>
            <td width="9%" align="right">数量</td>
            <td width="6%"></td>
            <td width="10%"></td>
        </tr>
        <asp:repeater id="rShoppingCart" Runat="server" OnItemCreated="rShoppingCart_ItemCreated">
        <ItemTemplate>
            <tr align="center" id='<%# "ShoppingCart_row_"+product.Id %>'>
                <td>
                    <a href="/Product/ProductDetail.aspx?id=<%# product.Id %>" target="_blank"><%# Xnet.Common.Text.String.Left(product.ProName, 50)%></a>
                </td>
                <td>
                    <label class="original-price"><%# string.Format("{0:C}",product.ProPrice) %></label>
                </td>
                <td>
                    <label class="special-price"><%# string.Format("{0:C}", product.ProPrice * product.ProSpecialOffer)%>
                </label>&nbsp;&nbsp;/&nbsp;&nbsp;<span><%# string.Format("{0:C}", product.ProPost1)%></span>
                </td>
                <td align="right">
                    <input type="text" id='<%# "ShoppingCart_row_txtproNumber" + product.Id %>' value='<%# product.ProNumber %>' style="30px;text-align:center" maxlength="4"
                    onblur='<%# string.Format("ChangePro_number({0},this)",product.Id) %>'/>
                </td>
                <td align="center"><div id='<%# "divDisplayMsg_" + product.Id %>'></div></td>
                <td>
                    <a style="cursor:pointer;" onclick='<%# string.Format("DeleteItem({0},this.parentNode.parentNode.id)",product.Id) %>'>删除</a>
                </td>
            </tr>
        </ItemTemplate>
        </asp:repeater>
      </table>
      <div class="more-choice">
     <div class="more-choice-link">
         <a onclick="javascript:window.close()" style="cursor:pointer">继续挑选商品&gt;&gt;</a><br />
            <a href="#" target="_blank"></a>
        </div>
        你共节省:<label id="lbltotPrice" class="special-price" runat="server"/>&nbsp;&nbsp;&nbsp;&nbsp;|
        <h3>商品金额总计:</h3>总计:
        <label id="lblnewtotPrice" runat="server" class="special-price" />
        <asp:Button ID="EnterToPay" runat="server" class="btn-bill"  Text="结算" OnClick="EnterToPay_Click" />   
      </div><!-- end more-choice -->
    </div><!-- end shopping-content -->

    <div style="margin-top: 10px;">
     <input type="button" value="清空" class="choice-btn" onclick="ClearItems()" />
    </div>

    后台代码
     
            //数据绑定
            private void ShoppingCartBind()
            {
                try
                {
                    GetCart();
                    IList<Product> list = cart.GetNewCartItems();

                    if (list != null)
                    {
                        rShoppingCart.DataSource = cart.GetShoppingCartList();
                        rShoppingCart.DataBind();

                        lbltotPrice.InnerText = string.Format("{0:C}", cart.TotalPrice - cart.TotalNewPrice);
                        lblnewtotPrice.InnerText = string.Format("{0:C}", cart.TotalNewPrice);
                    }
                    else
                    {
                        lbltotPrice.InnerText = string.Format("{0:C}", 0);
                        lblnewtotPrice.InnerText = string.Format("{0:C}", 0);
                    }
                }
                catch (Exception ex)
                {
                    Xnet.Common.WebUtils.MessageBox.Show(Page, ex.Message);
                }
            }

            //创建行事件
            protected Product product = null;
            protected void rShoppingCart_ItemCreated(object sender, RepeaterItemEventArgs e)
            {
                product = e.Item.DataItem as Product;
            }


    JS代码

    不过在用Cookie保存序列化信息时遇到个很严重的问题,就是说,我刚序列化对象到Cookie里, 接着取出来时,发现没能更新到最新数据,而是上一次信息,其实数据已经序列化到Cookie里了,这个问题我还没能解决,还得去找答案,用过Cookie和Session的结合应用,但是最后还是不理想...也许是我能力有限,js里的价格计算这个步骤原来是没必要的,但是受上面这个问题的影响,先这样。
     //更新购物车商品数量
        function ChangePro_number(id,obj)
        {
            if(isNaN(obj.value))
            {
                obj.value = 1;
            }
            else
            {
                var vali = /^0\d{0,4}$/.test(obj.value);
                if(vali)
                {
                    obj.value = 1;
                }
            }
            var divDisplay = document.getElementById("divDisplayMsg_"+id);
           
            var result = OrderSystemCtrl.AjaxMsg.AjaxMethods.UpdateProductNum(id,obj.value);
            if(result != null)
            {
                var dt = result.value;
                if(dt != null)
                {
                    if(parseInt(obj.value) == parseInt(dt[0]))
                    {
                        divDisplay.innerHTML = "更新成功";
                    }
                    else
                    {
                        divDisplay.innerHTML = "库存不足";
                    }
                    obj.value = dt[0];
                    GetPrice();
                }
            }
            else
            {
                divDisplay.innerHTML = "更新失败";
                return;
            }
        }
       
        //删除购物车记录
        function DeleteItem(id,nodeName)
        {
            if(confirm("确定要删除该商品?"))
            {
                var result = OrderSystemCtrl.AjaxMsg.AjaxMethods.DeleteProduct(id);
                if(result != null)
                {
                    if(result.value != null)
                    {
                        if(result.value.toLowerCase() == "success")
                        {
                            var rowid = document.getElementById(nodeName);
                            if(rowid != null)
                            {
                                rowid.parentNode.removeChild(rowid);
                            }
                           
                            var dt = result.value;
                            GetPrice();
                        }
                        else
                        {
                            alert(result.value);
                        }
                    }
                }
            }
        }
       
        //清空购物车
        function ClearItems()
        {
            if(confirm("确定要清空购物车所有的商品?"))
            {
                var result = OrderSystemCtrl.AjaxMsg.AjaxMethods.ClearProduct();
                if(result != null)
                {
                    if(result.value != null)
                    {
                        if(result.value.toLowerCase() == "success")
                        {
                            var cart = document.getElementsByTagName("TR");
                            if(cart != null && cart != "undefined")
                            {
                                var row = null;
                                var b = false;
                                for(var i=0; i<cart.length; i++)
                                {
                                    row = cart[i];
                                    if(row.id.indexOf("ShoppingCart_row_") > -1)
                                    {
                                        b = true;
                                        break;
                                    }
                                }
                                if(b == true)
                                {
                                    var parent = row.parentNode;
                                    for(var j=0; j<parent.childNodes.length-1; )
                                    {  
                                        parent.removeChild(parent.childNodes[1]);
                                    }
                                }
                                GetPrice();
                            }
                         }   
                         else
                         {
                            alert(result.value);
                         }
                     }
                 }
            }
        }
       
        //计算价格
        function GetPrice()
        {
            var Row = document.getElementsByTagName("TR");
            if(Row != null && Row != "undefined")
            {
                var newString="";
                for(var i=0; i<Row.length; i++)
                {
                    var row_i = Row[i];
                    var row_id = row_i.id;
                    if(row_id.indexOf("ShoppingCart_row_") > -1)
                    {
                        var id = row_id.substr(17);
                        var proNumber_id = "ShoppingCart_row_txtproNumber"+id;
                        var num = document.getElementById(proNumber_id).value;
                        newString = newString + (id+'|'+num+',');
                    }
                }
                var result = OrderSystemCtrl.AjaxMsg.AjaxMethods.GetFormatPrice(escape(newString));
                if(result != null)
                {
                    var dt = result.value;
                    var tot = document.getElementById("ctl00_ContentPlaceHolder1_ShoppingCart_lbltotPrice");
                    var newtot = document.getElementById("ctl00_ContentPlaceHolder1_ShoppingCart_lblnewtotPrice");
                    tot.innerHTML = dt[0];
                    newtot.innerHTML = dt[1];
                }                    
            }
        }

  • 相关阅读:
    IE兼容问题,各类css hack代码(亲测有效)
    javascript进阶系列专题:闭包(Closure)
    javascript进阶系列专题:作用域与作用域链
    github文件上传及github pages博客搭建教程
    javascript算法
    【CSS3】标签使用说明
    【html5】常见标签使用说明(持续更新)
    通过一行代码学习javascript
    Object.create()兼容实现方法
    oracle查询锁表解锁语句 (转)
  • 原文地址:https://www.cnblogs.com/di305449473/p/1207283.html
Copyright © 2011-2022 走看看