小型购物网站购物车功能实例

本文通过HTML技术详细讲解如何构建小型购物网站的购物车功能,涵盖了从添加商品到结算的完整流程,适合初学者实践。
摘要由CSDN通过智能技术生成

HTML

<form runat="server" style="margin-top:80px;">
    <script src="/Utility/jquery.cookie.js"></script>
    <div class="text-center list-empty hide" id="empty">
        <img src="/images/shopcar_noing.png" />
        <p><a href="Default.aspx" class="btn_orange_m" style="border-radius:8px;">返回商城</a></p>
    </div>
    <div class="p_like hide" style="display:none;">
        <div style="position:relative;">
            <span style="position:relative;display: inline-block;width:100%;height:1px;background:#ccc;z-index: 0;"></span>
            <h3>猜你喜欢</h3>
        </div>
        <div class="members_con" style="margin:0;">
            <section class="members_goodspic mt_0">
                <ul>
                    <%
                    <Hi:WapTemplatedRepeater ID="rp_guest" runat="server" TemplateFile="Tags/skin-Common_Guest.ascx" />%>
                </ul>
            </section>
        </div>
    </div>
    <style>
    </style>
    <div id="cart">
        <div class="item_content">
            <div class="shoppingStepBar clearfix">
                <h3 class="title">农哒商城</h3>
                <a href="#" id="eidt"><span>编辑</span><font style="display:none">完成</font></a>
            </div>
        </div>
        <div class="item_content mt_15">
            <div id="cartProducts">
                <hi:WapTemplatedRepeater id="rptCartProducts" templatefile="/Tags/skin-Common_CartProducts.ascx" runat="server" />
                <hi:waptemplatedrepeater id="rptCartGifts" runat="server" templatefile="/Tags/Skin-Common_WAPGiftList.ascx" />
            </div>
            <p class="notes" id="storeNotes" style="display:none;">购物车内有支持上门自提商品,<span οnclick="selectGetBySelf()">仅提交支持自提的商品。</span></p>
        </div>
        <div class="cart_info">
            <div class="cart_info_left">
                <label class="label-checkbox item-content">
                    <input type="checkbox" id="chk_list" />
                    <div class="item-media"><i class="icon icon-form-checkbox" id="test"></i></div>
                </label>
                <span id="spanAllSelect"> 全选</span>
            </div>
            <div class="cart_price">
                <span>
                    总价:
                    <strong id="totalPrice"><asp:literal runat="server" id="litTotal" ClientIDMode="Static" /></strong>
                </span>
                <span>
                    消费积分:
                    <strong id="PresentIntegral"><asp:literal runat="server" id="litPresentIntegral" ClientIDMode="Static" /></strong>
                </span>
            </div>
        </div>
        <a id="aLink" href="SubmmitOrder.aspx" class="pay">
            结算
        </a>
        <div class="cart_delete">
            <a id="btnClearCart" class="pay">删除</a>
        </div>
    </div>
    <input type="hidden" runat="server" id="hidUserPoints" />
    <input type="hidden" id="hidIsOpenStore" runat="server" value="" clientidmode="static" /><!-- 系统是否开启门店 -->
    <hi:Common_ContextMenu id="ContextMenu" runat="server" />
    <script type="text/javascript">
        $(function () {
            var imgh = $("body").width();
            $(".b_mingoods_wrapper").width(imgh / 2 - 25);
            var imgw = $(".b_mingoods_wrapper").width(imgh / 2 - 52);
            $(".members_goodspic ul li img").width(imgh / 2 - 30);
            $(".members_goodspic ul li img").height(imgh / 2 - 30);
        });
        $("#cartProducts input[type='checkbox']").change(function () {
            if ($("#cartProducts input[type='checkbox']:checked").length == $("#cartProducts input[type='checkbox']").length) {
                $('#chk_list').prop("checked", true)
            } else {
                $('#chk_list').prop("checked", false)
            }
        })
        $('#all').click(function () {
            $("input[type='checkbox']").prop("checked", this.checked); //改变多选框状态
        });
        $(document).ready(function () {
            if (!$.trim($('#cartProducts').html())) {
                $('#cart').addClass('hide');
                $('#empty').removeClass('hide');
                $('.p_like').removeClass('hide');
            }
            if ($('input[name="buyNum"]').size() <= 0) {
                $("#eidt").hide();
                $("#spanAllSelect").hide();
                $("#chkAllSelect").hide();
            }
            $('#chk_list').click(function () {
                $("input[name='ck_productId']").prop("checked", this.checked);
                changeBuyProduct();
            });
            $("#eidt").click(function () {
                $(".cart_delete").toggle();
                $("#eidt span").toggle();
                $("#eidt font").toggle();
                $(".cart_price").toggle();
                $("#aLink").toggle();
                $(".name").toggle();
                $(".cart_num").toggle();
                $(".icon_trash").toggle();
                $(".info_b").toggle();
                $(".pro_num").toggle();
                if ($("#eidt span").is(":visible")) {
                    changeBuyProduct()
                }else{
                }
            });
            changeBuyProduct();
        });
        //修改了勾选的商品
        function changeBuyProduct() {
            var ckids = getSelectProductckids();
            var amount = getSelectProductAmount();
            $.cookie("ckids", ckids, {
                expires: 3
            });
            $.ajax({
                url: "/API/ShoppingCartHandler.ashx",
                type: "post",
                dataType: "json",
                timeout: 10000,
                data: {
                    ckids: ckids
                },
                async: false,
                success: function (data) {
                    
                    if (data.status == undefined) {
                        $("#totalPrice").text('€' + data.StrTotalAmount);
                        $("#PresentIntegral").text( Number(data.StrTotalPresentIntegral).toFixed(2));
                        if (data.StrTotalAmount == 0) {
                            //判断是否有积分礼品
                            if ($('input[name="ck_productId"]').size() > 0) {
                                $("#aLink").attr("href", "SubmmitOrder.aspx");
                            }
                            else {
                                $("#aLink").attr("href", "javascript:alert_h('没有选择任何商品')");
                            }
                        }
                        else {
                            $("#aLink").attr("href", "SubmmitOrder.aspx?productSku=" + ckids);
                        }
                    } else {
                        $("#aLink").attr("href", "javascript:alert_h('" + data.msg + "')");
                    }
                }
            });
        }
        $("#btnClearCart").click(function (e) {
            var ckids = getSelectProductckids();
            if (ckids == "") {
                alert_h("没有选择任何商品");
                return false;
            }
            deleteProducts(ckids);
        });
        // 删除购物车商品
        function deleteProducts(ckids) {
            myConfirmBox('询问', '确定要从购物车里删除该商品吗?', '确认删除', '取消', function () {
                $.ajax({
                    url: "/API/ShoppingCartHandler.ashx",
                    type: "post",
                    dataType: "json",
                    timeout: 10000,
                    data: {
                        ck_productId: ckids,
                        action: "ClearCart"
                    },
                    async: false,
                    success: function (data) {
                        if (data.status == "true") {
                            document.location.href = "ShoppingCart.aspx?rnd=" + Math.random();
                        }
                        else {
                            alert_h(data.msg);
                        }
                    }
                });
            }, null);
        }
        // 获取选中购买的产品
        function getSelectProductckids() {
            var chk = $(":checkbox[name=ck_productId]:checked");
            var ck_productId = "";
            $(chk).each(function () {
                ck_productId += $(this).val() + ",";
            });
            ck_productId = ck_productId.substring(0, ck_productId.length - 1);
            return ck_productId;
        }
        // 获取选中购买的产品数量
        function getSelectProductAmount() {
            var buyNum = $("input[name=buyNum]");
            var amount = 0;
            $(buyNum).each(function () {
                if ($(this).parent().parent().find(":checkbox[name=ck_productId]:checked").length > 0) {
                    amount += parseInt($(this).val());
                }
            });
            return amount;
        }
        $(function () {
            $(".info_b_pu").hide();
            if ($("#hidIsOpenStore").val() == "true") {
                productHasStore();   //显示商品上门自提
            }
            else {
                $("#storeNotes").hide();
            }

            $("#eidt").click(function () {
                
                $(".cart_num").each(function () {
                    var test = $(this).siblings(".pro_num").children(".ui_textinput").val();
                    $(this).text("x" + test);
                })
            })
            if (!$.trim($('#cartProducts').html())) {
                $('#cart').addClass('hide');
                $('#empty').removeClass('hide');
                $('.p_like').removeClass('hide');
            }
            $('div[name="spAdd"]').bind("click", function () {
                var number = $(this).parent().find('[name="buyNum"]');
                number.val(parseInt(number.val()) + 1);
                var skuId = $(this).attr("skuid");
                chageCartProductQuantity(number, skuId);
            });
            $('div[name="spSub"]').bind("click", function () {
                var number = $(this).parent().find('[name="buyNum"]');
                var skuId = $(this).attr("skuid");

                var num = parseInt(number.val()) - 1;
                if (num > 0) number.val(parseInt(number.val()) - 1);
                chageCartProductQuantity(number, skuId);
            });
            $('[name="buyNum"]').unbind('blur').blur(function () {
                var skuId = $(this).attr("skuid");
                chageCartProductQuantity(this, skuId);
            });
            $('div[name="spGiftAdd"]').bind("click", function () {
                var currentPoints = $("#vShoppingCart_hidUserPoints").val();
                var txtBuyNum = $(this).parent().find('[name="buyGiftNum"]');
                var needPoint = txtBuyNum.attr("needPoints");
                var currentNum = parseInt(txtBuyNum.val());
                currentNum = currentNum + 1;
                txtBuyNum.val(currentNum);
                chageCartGiftQuantity(txtBuyNum);
            });
            $('div[name="spGiftSub"]').bind("click", function () {
                var number = $(this).parent().find('[name="buyGiftNum"]');
                var num = parseInt(number.val()) - 1;
                if (num > 0) number.val(parseInt(number.val()) - 1);
                chageCartGiftQuantity(number);
            });
            $('[name="buyGiftNum"]').unbind('blur').blur(function () {
                var currentPoints = $("#vShoppingCart_hidUserPoints").val();
                var needPoint = $(this).attr("needPoints");
                var currentNum = parseInt($(this).val());
                if (needPoint * currentNum > currentPoints) {
                    alert_h("您的积分不足");
                    $(this).val(1);
                }
                chageCartGiftQuantity(this);
            });
        });
        function chageCartProductQuantity(obj, skuId) {
            $.ajax({
                url: "/API/VshopProcess.ashx",
                type: 'post',
                dataType: 'json',
                timeout: 10000,
                data: {
                    action: "ChageQuantity",
                    skuId: $(obj).attr("skuId"),
                    quantity: parseInt($(obj).val())
                },
                success: function (resultData) {
                   
                    if (resultData.Status != "OK") {
                        alert("最多只可购买" + resultData.Status + "件");
                    } else {
                        $("i[gid=giftNum_" + skuId).text(parseInt($(obj).val()));
                        $("#spanPrice" + skuId).html(resultData.adjustedPrice);
                    }
                }
            });
        }
        function chageCartGiftQuantity(obj) {
            $.ajax({
                url: "/API/VshopProcess.ashx",
                type: 'post',
                dataType: 'text',
                timeout: 10000,
                data: {
                    action: "ChageGiftQuantity",
                    giftId: $(obj).attr("giftId"),
                    quantity: parseInt($(obj).val())
                },
                success: function (resultData) {
                    if (resultData.length > 0) {
                    }
                }
            });
        }
        function onGiftClick(obj, giftId) {
            myConfirmBox('询问', '确定要从购物车里删除该礼品吗?', '确认删除', '取消', function () {
                $.ajax({
                    url: "/API/VshopProcess.ashx",
                    type: 'post',
                    dataType: 'text',
                    timeout: 10000,
                    data: {
                        action: "DeleteCartGift",
                        giftId: giftId
                    },
                    success: function (aa) {
                        if (aa == "OK") {
                            $(obj).parent().parent().parent().remove();
                        }
                    }
                });
            });
        }
        //判断商品是否支持上门自提
        function productHasStore() {
            var productIds = "";
            $(".info_b_pu").each(function () {
                var productId = $(this).attr("productId");
                productIds += productId + ",";
            })
            if (productIds != "")
                productIds = productIds.substring(0, productIds.lastIndexOf(","));
            $.ajax({
                url: "/API/ShoppingCartHandler.ashx",
                type: "post",
                dataType: "json",
                timeout: 10000,
                data: { action: 'ProductsHasStore', productIds: productIds },
                async: false,
                success: function (data) {
                    if (data.status == 'true') {
                        var hasStoreProductIds = data.productIds;
                        if (hasStoreProductIds.length > 0) {
                            var pids = hasStoreProductIds.split(",");
                            for (var i = 0; i < pids.length; i++) {
                                var productid = pids[i];
                                $(".info_b_pu[productId='" + productid + "']").show();
                            }
                            if ($(".info_b_pu").length == pids.length) {
                                $("#storeNotes").hide();
                            } else {
                                $("#storeNotes").show();
                            }
                        }
                        else {
                            $("#storeNotes").hide();
                        }
                    }
                }
            });
        }
        function selectGetBySelf() {
            $(".info_b_pu").each(function () {
                var skuid = $(this).attr("skuid");
                if ($(this).is(":visible")) {
                    $("#ck_" + skuid).prop("checked", true);
                }
                else {
                    $("#ck_" + skuid).prop("checked", false);
                }
            });
            changeBuyProduct();
        }
    </script>
    <script src="/utility/vshoping.helper.js" type="text/javascript"></script>
    <script>
        //禁用右上角菜单
        document.addEventListener('WeixinJSBridgeReady', function onBridgeReady() {
            WeixinJSBridge.call('hideOptionMenu');
        });
    </script>
</form>


 
Skin-Common_CartProducts.ascx 

<%@ Control Language="C#" %>
<%@ Import Namespace="Hidistro.Core" %>
<%@ Import Namespace="Hidistro.UI.SaleSystem.CodeBehind" %>
<%@ Import Namespace="Hidistro.Entities.Promotions" %>
<%@ Register TagPrefix="Hi" Namespace="Hidistro.UI.Common.Controls" Assembly="Hidistro.UI.Common.Controls" %>
<div class="well goods-box goods-box-shopcart" style="margin-bottom:0;padding-bottom:0;border-bottom:1px solid #e7e5ea">

    <div class="cartlist_left">
        <label class="label-checkbox item-content" id="ck_productId">
            <input type="checkbox" οnclick="changeBuyProduct()" id="ck_<%# Eval("SkuId") %>" name="ck_productId" value="<%# Eval("SkuId") %>" />
            <div class="item-media"><i class="icon icon-form-checkbox"></i></div>
        </label>
    </div>
    <div class="info_border">
        <div class="info">
            <a href="<%# "ProductDetails.aspx?productId=" + Eval("ProductId")%>" class="cart_1">
                <Hi:ListImage ID="ListImage1" runat="server" DataField="ThumbnailUrl180" />
                <span class="info_b_pu" productid='<%# Eval("ProductId")%>' skuid='<%# Eval("SkuId")%>' style="display: none;">支持自提</span>
            </a>
            <div class="name font-xl bcolor">
                <a href="<%# "ProductDetails.aspx?productId=" + Eval("ProductId")%>">
                    <%# Eval("Name")%></a>
            </div>
            <div class="pro_num">
                <div name="spSub" class="shopcart-add" skuid='<%# Eval("SkuId")%>'>
                    -
                </div>
                <input type="number" class="ui_textinput" name="buyNum" value='<%# Eval("Quantity")%>'
                    skuid='<%# Eval("SkuId")%>' />
                <div name="spAdd" class="shopcart-minus" skuid='<%# Eval("SkuId")%>'>
                    +
                </div>
            </div>
            <div class="cart_sku">
                <asp:Literal ID="ltlSKUContent" runat="server"></asp:Literal>
            </div>
            <div class="cart_inte" style="clear:both;display:none;">
                <img style="width:25px;height:25px;vertical-align:sub;" src="../templates/common/images/icon_zuan.jpg" />
                <span style="color:rgb(189,217,11)"><%# Eval("ReturnConsumptionIntegral")%></span>
            </div>
                <input name="skucontent" type="hidden" value="<%# Eval("SkuContent")%>" />
                <input name="promotionName" type="hidden" value="<%#Convert.ToString(Eval("PromotionName"))%>" />
                <input name="promotionShortName" type="hidden" value="<%# PromotionHelper.GetShortName((PromoteType)Eval("PromoteType")) %>" />

            <div class="price text-danger" style="position:static;text-align:left;clear:both;">
                €  <span id="spanPrice<%# Eval("SkuId")%>"><%# Eval("AdjustedPrice", "{0:F2}")%></span>
            </div>
            <div class="price text-danger" style="position:static;text-align:left;color:#bdd90a">
                消费积分:<%# Eval("PresentIntegral", "{0:F2}")%></span>
            </div>
            <span class="cart_num">x<%# Eval("Quantity")%></span>
            <span class="icon_trash" οnclick="deleteProducts('<%#Eval("SkuId") %>')"></span>
        </div>
        <div class="info_b">
            <asp:Repeater ID="repProductGifts" runat="server">
                <ItemTemplate>
                    <span class="info_b_gift"><em>赠</em>  <%#Eval("Name").ToNullString().Length>18?Eval("Name").ToNullString().Substring(0,18)+"...": Eval("Name")%> <i gid='giftNum_<%# DataBinder.Eval((Container.Parent.NamingContainer.NamingContainer as RepeaterItem).DataItem, "SkuId") %>'>x<%#Eval("Quantity") %></i></span>
                </ItemTemplate>
            </asp:Repeater>
        </div>
    </div>
</div>
异步ajax

namespace Hidistro.UI.Web.API
{
    using Hidistro.Context;
    using Hidistro.Core;
    using Hidistro.Entities.Members;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.SaleSystem.Shopping;
    using Hidistro.SqlDal.Promotions;
    using Newtonsoft.Json;
    using System;
    using System.Linq;
    using System.Web;

    public class ShoppingCartHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/json";
            string str = context.Request["action"].ToNullString();
            if (!string.IsNullOrEmpty(str) && !(str == ""))
            {
                switch (str)
                {
                    case "HasStore":
                    {
                        string str7 = context.Request.Form["skuId"].ToNullString();
                        SiteSettings masterSettings = SettingsManager.GetMasterSettings();
                        if (string.IsNullOrEmpty(str7) || !masterSettings.OpenMultStore)
                        {
                            context.Response.Write("{\"status\":\"false\"}");
                            return;
                        }
                        if (ShoppingCartProcessor.HasStoreSkuStocks(str7))
                        {
                            context.Response.Write("{\"status\":\"true\"}");
                            return;
                        }
                        context.Response.Write("{\"status\":\"false\"}");
                        return;
                    }
                    case "ProductsHasStore":
                    {
                        string str8 = context.Request.Form["productIds"];
                        SiteSettings settings2 = SettingsManager.GetMasterSettings();
                        if (string.IsNullOrEmpty(str8) || !settings2.OpenMultStore)
                        {
                            context.Response.Write("{\"status\":\"false\"}");
                            return;
                        }
                        string str9 = ShoppingCartProcessor.HasStoreByProducts(str8);
                        context.Response.Write("{\"status\":\"true\",\"productIds\":\"" + str9 + "\"}");
                        return;
                    }
                    case "ClearCart":
                    {
                        string str5 = context.Request.Form["ck_productId"].ToNullString();
                        if (string.IsNullOrEmpty(str5))
                        {
                            context.Response.Write("{\"status\":\"false\",\"msg\":\"请选择要清除的商品\"}");
                        }
                        else
                        {
                            foreach (string str6 in str5.Split(new char[] { ',' }))
                            {
                                ShoppingCartProcessor.RemoveLineItem(str6);
                            }
                            context.Response.Write("{\"status\":\"true\",\"msg\":\"清除成功\"}");
                        }
                        context.Response.End();
                        return;
                    }
                }
                if (str == "updateBuyNum")
                {
                    SiteSettings ss = SettingsManager.GetMasterSettings();
                    string skuid = context.Request.Form["SkuId"].ToNullString().Trim();
                    int quantity = context.Request.Form["BuyNum"].ToNullString().Trim().ToInt();
                    ShoppingCartItemInfo info6 = ShoppingCartProcessor.GetShoppingCart(null, false).LineItems.FirstOrDefault<ShoppingCartItemInfo>(a => a.SkuId == skuid);
                    int num3 = (info6 == null) ? 1 : info6.Quantity;
                    if (quantity <= 0)
                    {
                        context.Response.Write("{\"status\":\"numError\",\"msg\":\"购买数量必须为大于0的整数\",\"oldNumb\":\"" + num3 + "\"}");
                    }
                    else if (ShoppingCartProcessor.GetSkuStock(skuid) < quantity)
                    {
                        context.Response.Write("{\"status\":\"StockError\",\"msg\":\"该商品库存不足\",\"oldNumb\":\"" + num3 + "\"}");
                    }
                    else
                    {
                        ShoppingCartProcessor.UpdateLineItemQuantity(skuid, quantity);
                        PromotionInfo productQuantityDiscountPromotion = ShoppingCartProcessor.GetProductQuantityDiscountPromotion(skuid, HiContext.Current.User.GradeId);
                        if ((productQuantityDiscountPromotion != null) && (quantity >= productQuantityDiscountPromotion.Condition))
                        {
                            info6.AdjustedPrice = info6.MemberPrice * productQuantityDiscountPromotion.DiscountValue;
                        }
                        else
                        {
                            info6.AdjustedPrice = info6.MemberPrice;
                        }
                        context.Response.Write("{\"status\":\"true\",\"adjustedPrice\":" + (info6.AdjustedPrice * Convert.ToDecimal(ss.ExchangeRate)).ToString("F2") + ",\"PresentIntegral\":" + info6.PresentIntegral .ToString("F2") + "}");
                    }
                }
                else
                {
                    switch (str)
                    {
                        case "updateGiftBuyNum":
                        {
                            string giftId = context.Request.Form["giftId"].ToNullString().Trim();
                            int num4 = context.Request.Form["BuyNum"].ToNullString().Trim().ToInt();
                            ShoppingCartGiftInfo info9 = ShoppingCartProcessor.GetShoppingCart(null, false).LineGifts.FirstOrDefault<ShoppingCartGiftInfo>(a => a.GiftId == giftId.ToInt());
                            if (info9 == null)
                            {
                                context.Response.Write("{\"status\":\"nullError\",\"msg\":\"该礼品不存在或已删除\",\"oldNumb\":\"" + 0 + "\"}");
                                return;
                            }
                            if (num4 <= 0)
                            {
                                context.Response.Write("{\"status\":\"numError\",\"msg\":\"购买数量必须为大于0的整数\",\"oldNumb\":\"" + info9.Quantity + "\"}");
                                return;
                            }
                            ShoppingCartProcessor.UpdateGiftItemQuantity(giftId.ToInt(), num4, PromoteType.NotSet);
                            context.Response.Write("{\"status\":\"true\"}");
                            return;
                        }
                        case "deleteGift":
                            ShoppingCartProcessor.RemoveGiftItem(context.Request.Form["giftId"].ToNullString().Trim().ToInt(), PromoteType.NotSet);
                            context.Response.Write("{\"status\":\"true\"}");
                            return;

                        case "delete":
                            ShoppingCartProcessor.RemoveLineItem(context.Request.Form["SkuId"].ToNullString().Trim());
                            context.Response.Write("{\"status\":\"true\"}");
                            return;

                        case "deleteall":
                        {
                            string str12 = context.Request.Form["SkuIdList"].ToNullString().Trim();
                            if (!string.IsNullOrEmpty(str12.ToNullString().Trim()))
                            {
                                foreach (string str13 in str12.TrimStart(new char[] { ',' }).TrimEnd(new char[] { ',' }).Split(new char[] { ',' }))
                                {
                                    ShoppingCartProcessor.RemoveLineItem(str13);
                                }
                            }
                            context.Response.Write("{\"status\":\"true\"}");
                            return;
                        }
                        case "reducedpromotion":
                        {
                            decimal amount = context.Request.Form["Amount"].ToDecimal();
                            int num6 = context.Request.Form["Quantity"].ToInt();
                            MemberInfo user = HiContext.Current.User;
                            decimal reducedAmount = 0M;
                            PromotionInfo info11 = new PromotionDao().GetReducedPromotion(user.GradeId, amount, num6, out reducedAmount);
                            if (info11 != null)
                            {
                                context.Response.Write(string.Concat(new object[] { "{\"ReducedPromotionAmount\":\"", reducedAmount, "\",\"ReducedPromotionCondition\":\"", info11.Condition, "\"}" }));
                                return;
                            }
                            context.Response.Write("{\"ReducedPromotionAmount\":\"0\",\"ReducedPromotionCondition\":\"0\"}");
                            break;
                        }
                    }
                }
            }
            else
            {
                string currentBuyProductckIds = string.Empty;
                string str3 = context.Request["ckids"];
                if (!string.IsNullOrEmpty(str3))
                {
                    currentBuyProductckIds = str3;
                }
                ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(currentBuyProductckIds, true);
                string[] source = currentBuyProductckIds.Split(new char[] { ',' });
                bool flag = false;
                foreach (ShoppingCartItemInfo info2 in shoppingCart.LineItems)
                {
                    if (source.Contains<string>(info2.SkuId) && (ShoppingCartProcessor.GetSkuStock(info2.SkuId) < info2.Quantity))
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    context.Response.ContentType = "text/json";
                    context.Response.Write("{\"status\":\"false\",\"msg\":\"有商品库存不足,不能结算\"}");
                    context.Response.End();
                }
                if (shoppingCart != null)
                {
                    ShoppingCartGiftInfo info3 = (from a in shoppingCart.LineGifts
                        where a.PromoType == 5
                        select a).FirstOrDefault<ShoppingCartGiftInfo>();
                    shoppingCart.SendGiftPromotionId = (info3 == null) ? 0 : info3.GiftId;
                    if (!shoppingCart.IsSendGift && (shoppingCart.LineGifts.Count > 0))
                    {
                        foreach (ShoppingCartGiftInfo info4 in shoppingCart.LineGifts)
                        {
                            ShoppingCartProcessor.RemoveGiftItem(info4.GiftId, PromoteType.SentGift);
                        }
                    }
                }
                string s = JsonConvert.SerializeObject(shoppingCart);
                context.Response.ContentType = "text/json";
                context.Response.Write(s);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

CS

namespace Hidistro.UI.SaleSystem.CodeBehind
{
    using Hidistro.Context;
    using Hidistro.Core;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.SaleSystem.Catalog;
    using Hidistro.SaleSystem.Shopping;
    using Hidistro.UI.Common.Controls;
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;

    [ParseChildren(true)]
    public class WAPShoppingCart : WAPMemberTemplatedWebControl
    {
        private HtmlInputHidden hidIsOpenStore;
        private HtmlInputHidden hidUserPoints;
        private Literal litTotal;
        private Literal litPresentIntegral;
        private Repeater rp_guest;
        private WapTemplatedRepeater rptCartGifts;
        private WapTemplatedRepeater rptCartProducts;

        protected override void AttachChildControls()
        {
            SiteSettings masterSettings = SettingsManager.GetMasterSettings();
            this.rptCartProducts = (WapTemplatedRepeater)this.FindControl("rptCartProducts");
            this.rptCartGifts = (WapTemplatedRepeater)this.FindControl("rptCartGifts");
            this.litTotal = (Literal)this.FindControl("litTotal");
            this.litPresentIntegral = (Literal)this.FindControl("litPresentIntegral");
            this.rp_guest = (Repeater)this.FindControl("rp_guest");
            this.hidUserPoints = (HtmlInputHidden)this.FindControl("hidUserPoints");
            this.hidIsOpenStore = (HtmlInputHidden)this.FindControl("hidIsOpenStore");
            ShoppingCartInfo shoppingCart = ShoppingCartProcessor.GetShoppingCart(null, true);
            //for (int i = 0; i < shoppingCart.LineItems.Count;i++ )
            //{
            //    shoppingCart.LineItems[i].AdjustedPrice = shoppingCart.LineItems[i].AdjustedPrice * Convert.ToDecimal(masterSettings.ExchangeRate);
            //}
            if (shoppingCart != null)
            {
                this.rptCartProducts.ItemDataBound += new RepeaterItemEventHandler(this.rptCartProducts_ItemDataBound);
                this.rptCartProducts.DataSource = shoppingCart.LineItems;
                this.rptCartProducts.DataBind();
                this.litTotal.Text = shoppingCart.GetAmount().ToString("F2");
                this.litPresentIntegral.Text = shoppingCart.GetPresentIntegral().ToString("F2");
                if (shoppingCart.LineGifts.Count > 0)
                {
                    IEnumerable<ShoppingCartGiftInfo> enumerable = from s in shoppingCart.LineGifts
                                                                   where s.PromoType == 0
                                                                   select s;
                    this.rptCartGifts.DataSource = enumerable;
                    this.rptCartGifts.DataBind();
                }
            }
            if (this.rp_guest != null)
            {
                IList<int> browedProductList = BrowsedProductQueue.GetBrowedProductList(10);
                this.rp_guest.DataSource = ProductBrowser.GetVistiedProducts(browedProductList);
                this.rp_guest.DataBind();
            }
            if (HiContext.Current.UserId > 0)
            {
                this.hidUserPoints.Value = HiContext.Current.User.Points.ToString();
            }
            this.hidIsOpenStore.Value = masterSettings.OpenMultStore ? "true" : "false";
            PageTitle.AddSiteNameTitle("购物车");
            Repeater repeater = new Repeater();
        }

        protected void btnClearCart_Click(object sender, EventArgs e)
        {
            string str = this.Page.Request.Form["ck_productId"];
            if (string.IsNullOrEmpty(str))
            {
                this.ShowMessage("请选择要清除的商品", false);
            }
            else
            {
                foreach (string str2 in str.Split(new char[] { ',' }))
                {
                    ShoppingCartProcessor.RemoveLineItem(str2);
                }
            }
            this.Page.Response.Redirect("ShoppingCart.aspx", true);
        }

        protected override void OnInit(EventArgs e)
        {
            if (this.SkinName == null)
            {
                this.SkinName = "Skin-VShoppingCart.html";
            }
            base.OnInit(e);
        }

        private void rptCartProducts_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if ((HiContext.Current.User.UserId != 0) && ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)))
            {
                Control control = e.Item.Controls[0];
                Literal literal = control.FindControl("ltlSKUContent") as Literal;
                Repeater repeater = control.FindControl("repProductGifts") as Repeater;
                ShoppingCartItemInfo itemInfo = e.Item.DataItem as ShoppingCartItemInfo;
                string[] strArray = itemInfo.SkuContent.Split(new char[] { ';' });
                string str = string.Empty;
                foreach (string str2 in strArray)
                {
                    string[] strArray2 = str2.Split(new char[] { (char)0xff1a });
                    if (strArray2.Length == 2)
                    {
                        str = str + " " + strArray2[1] + " /";
                    }
                }
                str = str.TrimEnd(new char[] { '/' });
                literal.Text = str;
                PromotionInfo productPromotionInfo = ProductBrowser.GetProductPromotionInfo(itemInfo.ProductId);
                if ((productPromotionInfo != null) && (productPromotionInfo.PromoteType == PromoteType.SentGift))
                {
                    List<ShoppingCartGiftInfo> cartGiftList = new List<ShoppingCartGiftInfo>();
                    ProductBrowser.GetGiftDetailsByGiftIds(productPromotionInfo.GiftIds).ForEach<GiftInfo>(delegate(GiftInfo gift)
                    {
                        ShoppingCartGiftInfo item = new ShoppingCartGiftInfo
                        {
                            GiftId = gift.GiftId,
                            CostPrice = gift.CostPrice.HasValue ? gift.CostPrice.Value : 0M,
                            PromoType = 5,
                            Quantity = itemInfo.ShippQuantity,
                            Weight = gift.Weight,
                            Volume = gift.Volume,
                            NeedPoint = gift.NeedPoint,
                            Name = gift.Name,
                            ThumbnailUrl100 = gift.ThumbnailUrl100,
                            ThumbnailUrl180 = gift.ThumbnailUrl180,
                            ThumbnailUrl40 = gift.ThumbnailUrl40,
                            ThumbnailUrl60 = gift.ThumbnailUrl60,
                            IsExemptionPostage = gift.IsExemptionPostage,
                            ShippingTemplateId = gift.ShippingTemplateId
                        };
                        cartGiftList.Add(item);
                    });
                    repeater.DataSource = cartGiftList;
                    repeater.DataBind();
                }
            }
        }
    }
}





 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值