Exemplo n.º 1
0
        public ActionResult SaveOrder(Models.OrderModel orderModel)
        {
            try
            {
                List <OrderDetailsModel> orderDetailsModels = new List <OrderDetailsModel>();
                var models = this.ShopServices.GetShopCart();
                if (models.Count() == 0)
                {
                    throw new Exception();
                }

                foreach (var item in models)
                {
                    var newModel = new OrderDetailsModel()
                    {
                        Item  = item.ProdName,
                        Count = (int)item.Count,
                        Price = item.Price,
                    };
                    orderDetailsModels.Add(newModel);
                }


                using (var db = new EF.DBContext())
                {
                    orderModel.OrderDate         = DateTime.Now;
                    orderModel.Amount            = this.ShopServices.ProdAmount;
                    orderModel.OrderDetailModels = orderDetailsModels;
                    db.Orders.Add(orderModel);
                    db.SaveChanges();
                }

                var c = new HttpCookie("shopcart")
                {
                    Expires = DateTime.Now.AddDays(-1)
                };
                Response.Cookies.Add(c);

                ViewData["Message"] = "訂購成功。";
            }
            catch (Exception ex)
            {
                ViewData["Message"] = $"訂購失敗。({ex.Message})";
            }

            return(View());
        }
Exemplo n.º 2
0
        public List <Models.ProductModel> GetShopCart()
        {
            List <Models.ProductModel> productModels = new List <Models.ProductModel>();
            HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(CookieName);

            if (cookie != null)
            {
                string str = string.Empty;
                if (string.IsNullOrEmpty(cookie.Value))
                {
                    return(productModels);
                }

                var array  = cookie.Value.Split(',');
                var length = array.Length;
                for (int i = 0; i < length; i = i + 2)
                {
                    var id    = Convert.ToInt32(array[i].Replace("ID=", ""));
                    var count = Convert.ToInt32(array[i + 1].Replace("COUNT=", ""));

                    using (var db = new EF.DBContext())
                    {
                        var model = db.Products.Find(id);

                        if (model == null)
                        {
                            continue;
                        }
                        model.Count      = count;
                        this.ProdAmount += model.Count * model.Price;
                        productModels.Add(model);
                    }
                }
            }
            return(productModels);
        }