我在javascript / json和ASP MVC中遇到一些购物车的问题
方案: 主要功能是订购产品但不是1个用户的普通购物车,它可以是2个用户,3个用户,1个用户等,但只有1个购物车(javascript对象)。这取决于具体的买方。所以主要的问题是,如果买方为user1购买“蛋糕”,然后想要购买具有不同日期和相同“蛋糕”的用户2,那么该产品将是“2个蛋糕”但是对于第二个用户,第一个用户丢失了“蛋糕”。
我需要特定蛋糕用户和日期。因此,如果买方为2014年5月1日的用户1购买蛋糕(例如使用日期选择器),然后为2014年5月2日的用户2购买蛋糕(例如使用日期选择器),每个用户的产品数量为1,而不是数量为2的蛋糕。
实际上我正在使用像这样的购物车的javascript对象
var ShoppingCart = {
BuyerID: 1, //I will handle this later
StoreID: 1,
Total: 0,
ShoppingCartItems: [] //array with json objects
};
然后我正在使用一个函数将按钮上需要的元素推送到数组
function AddItem (ProductID,ProductName, Description, Price, Quantity, StoreID){
var UserID = $("#hiddenUserID").val(); //e.g. = 1
var ProductDate = $("#hiddenDateField").val(); //e.g. = 2014/05/01
ShoppingCartItems.push({
"ProductID": ProductoID,
"ProductName": ProductName,
"Description": Description,
"Price": Price,
"Quantity": Quantity,
"StoreID": StoreID,
"UserID": UserID, //this will change later
"ProductDate": ProductDate //this will change if the buyer choose another day
})
}
每次买方点击按钮时,此功能都有效。产品加载了ajax,这不是问题所在。用户从产品中选择后,将使用所选产品和我使用的所有规格创建新阵列。所以我有2个问题
如果买方选择例如1个蛋糕,但他忘记了他需要2个蛋糕,如果他再次点击第2个蛋糕,阵列将推送新元素或数量为1的其他产品
我想如果产品具有相同的ProductID,userID和日期,将数量更新为2个蛋糕,因为第二个问题来自第一个,我需要通过ProductID,userID和date更新数量,因为如果买方计划为每个用户购买蛋糕,产品需要分开,例如这样就错了:
userID = 1的产品
userID = 2的产品
我希望数组的productID,userID和日期的数量是分开的,因此每个产品都需要在userID和日期之间有一个“链接”:
userID = 1的产品
userID = 2的产品
因此,如果user1和用户2在同一日期拥有相同的产品,我需要验证以按用户ID和DATE分隔每个产品的数量,这是一个大问题。
实际上我使用MVC所以这种方式是将json和ajax发送到特定模型的最佳方式(对于modelstate.isvalid)。所以这个代码被“测试”了我需要的东西,以便正确的数据到数据库。 希望有人能帮助我。
提前致谢
答案 0 :(得分:1)
当您将新商品推送到购物车时,您需要将其与购物车中的对象进行比较,如果产品ID,用户ID和日期匹配,则您需要将新数量添加到购物车数组中旧对象的旧数量,而不是推送新对象。或者,您可以在添加项目后处理购物车数组,并在添加其数量时合并重复项。我不确定哪种方法更好。
function AddItem (ProductID,ProductName, Description, Price, Quantity, StoreID) {
var merged = false;
var UserID = $("#hiddenUserID").val(); //e.g. = 1
var ProductDate = $("#hiddenDateField").val(); //e.g. = 2014/05/01
var newItemObj = {
"ProductID": ProductID,
"ProductName": ProductName,
"Description": Description,
"Price": Price,
"Quantity": Quantity,
"StoreID": StoreID,
"UserID": UserID,
"ProductDate": ProductDate
};
// loop through items in cart
for ( var i = 0; i < ShoppingCartItems.length; i++ ) {
// if product ID, user ID, and date are the same
if ( ShoppingCartItems[i].ProductID == newItemObj.ProductID &&
ShoppingCartItems[i].UserID == newItemObj.UserID &&
ShoppingCartItems[i].ProductDate == newItemObj.ProductDate ) {
// add the quantity of the new obj to the old one
ShoppingCartItems[i].Quantity += newItemObj.Quantity;
// if two items are merged, set a flag
merged = true;
}
};
// if no merge happened, just add the item normally
if ( !merged ) {
ShoppingCartItems.push( newItemObj );
}
}