public ActionResult cart(string pid, string pqty) { if (pid == null || pqty == null) { ViewBag.c = ok.c; return(View()); } if (pid == "0" && pqty == "0") { return(View()); } foreach (var item in ok.c) { if (item.iid == int.Parse(pid)) { item.iqty += int.Parse(pqty); ViewBag.c = ok.c; return(View()); } } cartitem i = new cartitem() { iid = int.Parse(pid), iqty = int.Parse(pqty) }; ok.c.Add(i); ViewBag.c = ok.c; return(View()); }
public void AddToCart(int id) { // Retrieve the product from the database. ShoppingCartId = GetCartId(); var cartItem = _db.coursecartitems.SingleOrDefault(c => c.CartId == ShoppingCartId && c.ProductID == id); if (cartItem == null) { // Create a new cart item if no cart item exists. cartItem = new cartitem { ItemId = Guid.NewGuid().ToString(), ProductID = id, CartId = ShoppingCartId, Product = _db.Products.SingleOrDefault(p => p.ProductID == id), Quantity = 1, DateCreated = DateTime.Now }; _db.coursecartitems.Add(cartItem); } else { // If the item does exist in the cart, // then add one to the quantity. cartItem.Quantity++; } _db.SaveChanges(); }
public static CartItem ToLiquidModel(this cartitem row, long?viewerid) { var item = new CartItem { id = row.id, quantity = row.quantity, price = row.product_variant.product.ToUserPrice(viewerid).Value, title = row.product_variant.ToProductFullTitle(), product = row.product_variant.product.ToLiquidModel(viewerid, "") }; item.variant = row.product_variant.ToLiquidModel(item.price); item.total_price = item.price * item.quantity; return(item); }
protected void baddtocart_Click(object sender, EventArgs e) { if (Session["isLogged"] != null && (bool)Session["isLogged"]) { if (Session["cart"] == null) { Session["cart"] = new ArrayList(); } int quantity = int.Parse(tquantity.Text); cartitem item = new cartitem(quantity, pid); ((ArrayList)Session["cart"]).Add(item); Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "alert('" + quantity.ToString() + " unit(s) added to cart');", true); } else { Response.Redirect("login.aspx"); } }
// Helper method to simplify shopping cart calls public string AddToCart(Product album) { Random rand = new Random(); // Get the matching cart and album instances var cartItem = storeDB.ShoppingCartItems.SingleOrDefault( c => c.CartID == ShoppingCartId && c.ProductID == album.ProductID); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new cartitem { ItemID = rand.Next().ToString(), ProductID = album.ProductID, CartID = ShoppingCartId, Quantity = 1, DateCreated = DateTime.Now }; storeDB.ShoppingCartItems.Add(cartItem); } else { // If the item does exist in the cart, // then add one to the quantity if (album.Quantity > cartItem.Quantity + 1) { cartItem.Quantity++; } else { return("Không đủ số lượng"); } } // Save changes storeDB.SaveChanges(); return("Thêm hàng thành công"); }
public ActionResult cart(string pid, string pqty) { foreach (var item in Ok.c) { if (item.iid == int.Parse(pid)) { item.iqty += int.Parse(pqty); ViewBag.c = Ok.c; return(View()); } } cartitem i = new cartitem() { iid = int.Parse(pid), iqty = int.Parse(pqty) }; Ok.c.Add(i); ViewBag.c = Ok.c; return(View()); }
// id = variant id public ActionResult Add(long id, int quantity = 1, bool isJson = false) { cart cart = null; var cartid = GetCartIdFromCookie(); // if not then we create cookie if (!string.IsNullOrEmpty(cartid)) { cart = MASTERdomain.carts.SingleOrDefault(x => x.id.ToString() == cartid); } if (cart == null) { cart = new cart { subdomainid = subdomainid.Value }; MASTERdomain.carts.Add(cart); } // check that we have enough products var variant = repository.GetProductVariants(subdomainid.Value).SingleOrDefault(x => x.id == id); if (variant == null) { return(Content(CreatePageMissingTemplate().Render())); } if (!variant.HasStock(quantity)) { var instock = variant.ToQuantity(); if (isJson) { return (Json(string.Format("We have only {0} of {1} left", instock, variant.ToProductFullTitle()).ToJsonFail())); } quantity = instock; } // add item to cart var item = cart.cartitems.SingleOrDefault(x => x.variantid == id); if (item != null) { item.quantity = quantity; } else { // only add if item has a price if (variant.product.sellingPrice.HasValue) { item = new cartitem(); item.variantid = id; item.quantity = quantity; cart.cartitems.Add(item); } } // save to db repository.Save(); // store cookie Response.Cookies["cart"].Value = cart.id.ToString(); Response.Cookies["cart"].Expires = DateTime.UtcNow.AddDays(GeneralConstants.COOKIE_LIFETIME); if (isJson) { var liquidmodel = item.ToLiquidModel(sessionid); return(Json(liquidmodel)); } return(RedirectToAction("Index")); }
protected void Page_Load(object sender, EventArgs e) { string action = Request.QueryString["action"]; ArrayList AL; //Hashtable HT; XmlTextWriter myXmlWriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8); string htmltext = ""; Page.Response.ContentType = "text/xml"; Page.Response.Charset = "utf-8"; /* Pagina che gestisce le chiamate AJAX provenienti dal client * invocate da vetrina_default.aspx. * utilizza i seguenti parametri URL: * - idlist: id dell'articolo in listino * - idstore: id magazzino * - idstock: id stock * - units: numero di unità da prenotare. * - action: azione da effetturare. Ha tre valori: * * add: aggiunge al carrello; * * show: mostra il contenuto attuale del carrello; * * empty: svuota il carrello. */ switch (action) { case "add": { /* Aggiunge articoli al carrello * necessita dei parametri idlist (id articolo), units (quantità), * idstore (id magazzino). Restituisce un XML che contiene * il messaggio di notifica di avvenuto inserimento dell'articolo nel carrello. */ int idlist = CfgFn.GetNoNullInt32(Request.QueryString["idlist"]); int quantity = CfgFn.GetNoNullInt32(Request.QueryString["units"]); int idstore = CfgFn.GetNoNullInt32(Request.QueryString["idstore"]); int idstock = CfgFn.GetNoNullInt32(Request.QueryString["idstock"]); decimal price = CfgFn.GetNoNullDecimal(HelpForm.GetObjectFromString(typeof(decimal), Request.QueryString["price"], "x.y.n")); if (idlist == null) { return; } if (quantity == null) { return; } if (Session["Cart"] == null) { AL = new ArrayList(); } else { AL = (ArrayList)Session["Cart"]; } // Find if an item with same idlist and idstore exists in arraylist cartitem CI; bool found = false; int index; int previousquantity = 0; for (index = 0; index < AL.Count; index++) { CI = (cartitem)AL[index]; if (CI.idlist == idlist && CI.idstore == idstore && CI.price == price && CI.idstock == idstock) { found = true; previousquantity = CI.quantity; break; } } if (found) { CI = new cartitem(); CI.idlist = idlist; CI.idstore = idstore; CI.quantity = quantity + previousquantity; CI.price = price; CI.idstock = idstock; AL[index] = CI; } else { CI = new cartitem(); CI.idlist = idlist; CI.idstore = idstore; CI.quantity = quantity; CI.price = price; CI.idstock = idstock; AL.Add(CI); } Session["Cart"] = AL; myXmlWriter.WriteStartDocument(); myXmlWriter.WriteStartElement("datagrid"); myXmlWriter.WriteStartElement("htmlcode"); htmltext += "<fieldset>"; htmltext += "<legend style=\"text-align :center\">Operazione Effettuata</legend>"; htmltext += "<div class=\"row\">"; htmltext += "<div class=\"col-md-5\"></div>"; htmltext += "<div class=\"col-md-4\">"; htmltext += "<label>Gli articoli da Lei scelti sono stati aggiunti al carrello</label>"; htmltext += "</div>"; htmltext += "<div class=\"col-md-3\"></div>"; htmltext += "</div>"; //chiude la rows htmltext += "</fieldset>"; myXmlWriter.WriteCData(htmltext); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("meta"); myXmlWriter.WriteStartElement("totalpages"); myXmlWriter.WriteValue("0"); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("title"); myXmlWriter.WriteValue(""); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.Flush(); myXmlWriter.Close(); break; } case "show": { /* Mostra il carrello corrente (se contiene articoli). * Restituisce un XML contenente il contenuto * del carrello corrente se esso contiene elementi, * altrimenti un XML contenente un messaggio di * "Carrello Vuoto" */ if (Session["Cart"] == null) { // Carrello vuoto myXmlWriter.WriteStartDocument(); myXmlWriter.WriteStartElement("datagrid"); myXmlWriter.WriteStartElement("htmlcode"); htmltext += "<div class=\"row\">"; htmltext += "<div class=\"col-md-5\"></div>"; htmltext += "<div class=\"col-md-4\">"; htmltext += "<label>Il suo carrello è vuoto.</label>"; htmltext += "</div>"; htmltext += "<div class=\"col-md-3\"></div>"; htmltext += "</div>"; //chiude la rows myXmlWriter.WriteCData(htmltext); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("meta"); myXmlWriter.WriteStartElement("totalpages"); myXmlWriter.WriteValue("0"); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("title"); myXmlWriter.WriteValue(""); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.Flush(); myXmlWriter.Close(); } else { // Visualizza il riepilogo // In base agli id nella HT si prelevano dal DB i codici e le descrizioni degli articoli. // E si visualizza il riepilogo AL = (ArrayList)Session["Cart"]; if (AL.Count == 0) { return; } DataAccess Conn = GetVars.GetUserConn(Page); QueryHelper QHS = Conn.GetQueryHelper(); cartitem CI; //htmltext += "<fieldset style=\"background-color: #eeeeee;\">"; htmltext += "<div class=\"row\">"; htmltext += "<div class=\"col-md-4\"></div>"; htmltext += "<div class=\"col-md-4\">"; htmltext += "<label>Articoli attualmente nel carrello</label>"; htmltext += "</div>"; htmltext += "<div class=\"col-md-4\"></div>"; htmltext += "</div>"; //chiude la rows htmltext += "<div class=\"row\">"; htmltext += "<div class=\"col-md-12\">"; htmltext += "<table class=\"table table-striped\";>"; //htmltext += "<thead><tr style=\"background-color:#d9edf7;color:#000000;\">"; htmltext += "<thead><tr>"; htmltext += "<thead><tr><th>Articolo</th><th>Class.Merceologica</th>"; htmltext += "<th>Quantità</th></tr></thead><tbody>"; int counter; string bgcolor = ""; for (counter = 0; counter < AL.Count; counter++) { CI = (cartitem)AL[counter]; //if (counter % 2 == 0) // bgcolor = "#d9edf7;";//bgcolor = "#eaeaea;"; //else // bgcolor = "#c4e3f3;";//bgcolor = "#bababa;"; bgcolor = "#FFFFFF"; string storedescription; string itemdescription; string filter; string listclass; string idlistclass; filter = QHS.CmpEq("idlist", CI.idlist); DataTable T; T = Conn.RUN_SELECT("list", "description,idlistclass", null, filter, null, false); itemdescription = T.Rows[0]["description"].ToString(); idlistclass = T.Rows[0]["idlistclass"].ToString(); filter = QHS.CmpEq("idlistclass", idlistclass); T = Conn.RUN_SELECT("listclass", "title", null, filter, null, false); listclass = T.Rows[0]["title"].ToString(); /* * filter = QHS.CmpEq("idstore", CI.idstore); * T = Conn.RUN_SELECT("store", "description", null, filter, null, false); * storedescription=T.Rows[0]["description"].ToString(); */ htmltext += "<tr style=\"background-color:" + bgcolor + "\">"; htmltext += "<td><style=\"text-align: justify;\">" + itemdescription + "</td>"; htmltext += "<td><style=\"text-align: left;\">" + listclass + "</td>"; htmltext += "<td><style=\"text-align: center;\">" + CI.quantity.ToString() + "</td>"; htmltext += "</tr>"; } htmltext += "</tbody></table>"; htmltext += "</div>"; // chiude class col-md-12 htmltext += "</div>"; //chiude la rows myXmlWriter.WriteStartDocument(); myXmlWriter.WriteStartElement("datagrid"); myXmlWriter.WriteStartElement("htmlcode"); myXmlWriter.WriteCData(htmltext); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("meta"); myXmlWriter.WriteStartElement("totalpages"); myXmlWriter.WriteValue("0"); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("title"); myXmlWriter.WriteValue(""); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.Flush(); myXmlWriter.Close(); } } break; case "empty": { /* Svuota il carrello corrente. * Restituisce un XML contenente il messaggio di notifica * dell'avvenuto svuotamento, oppure un messaggio di notifica * che avvisa l'utente che il carrello è già vuoto. */ // azzera il carrello if (Session["Cart"] == null) { htmltext += "<p>Il suo carrello è già vuoto.</p>"; } else { Session["Cart"] = null; htmltext += "<p>Il suo carrello è stato svuotato come richiesto.</p>"; } myXmlWriter.WriteStartDocument(); myXmlWriter.WriteStartElement("datagrid"); myXmlWriter.WriteStartElement("htmlcode"); myXmlWriter.WriteCData(htmltext); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("meta"); myXmlWriter.WriteStartElement("totalpages"); myXmlWriter.WriteValue("0"); myXmlWriter.WriteEndElement(); myXmlWriter.WriteStartElement("title"); myXmlWriter.WriteValue(""); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.WriteEndElement(); myXmlWriter.Flush(); myXmlWriter.Close(); } break; } Page.Response.End(); }
public string UpdateCart(List <cartitem> cart) { try { List <cartitem> oldcart = storeDB.ShoppingCartItems.Where(c => c.CartID == ShoppingCartId).ToList(); string s = ""; TMDTModel db = new TMDTModel(); Product album = new Product(); EmptyCart(); for (int i = 0; i < cart.Count; i++) { album = db.Products.Find(cart[i].ProductID); if (album.Quantity > cart[i].Quantity) { cartitem cartitem = new cartitem { ItemID = cart[i].ItemID, Quantity = cart[i].Quantity, ProductID = cart[i].ProductID, CartID = cart[i].CartID, DateCreated = cart[i].DateCreated }; storeDB.ShoppingCartItems.Add(cartitem); } else { cartitem cartitem = new cartitem { ItemID = cart[i].ItemID, Quantity = oldcart.Where(x => x.ItemID.Equals(cart[i].ItemID)).SingleOrDefault().Quantity, ProductID = cart[i].ProductID, CartID = cart[i].CartID, DateCreated = cart[i].DateCreated }; storeDB.ShoppingCartItems.Add(cartitem); s += "Số lượng sản phẩm " + album.ProductName + " Không đủ , "; } } storeDB.SaveChanges(); if (String.IsNullOrEmpty(s)) { return("Cập nhật thành công"); } else { return(s); } } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } }