예제 #1
0
        public IActionResult Product(int?id = null)
        {
            ViewBag.Vendors    = _VendorRepo.GetAll();
            ViewBag.Categories = _CategoryRepo.GetAll();

            var product = _ProductRepo.GetByID(id);

            ProductForm productForm;

            if (product != null)
            {
                productForm = ProductForm.FromModel(product);
            }
            else
            {
                productForm = new ProductForm();
            }

            return(View(productForm));
        }
예제 #2
0
        public IActionResult ProductEdit(ProductForm productForm)
        {
            ViewBag.Vendors    = _VendorRepo.GetAll();
            ViewBag.Categories = _CategoryRepo.GetAll();

            var zeroId = productForm.ID == 0;

            if (ModelState.IsValid)
            {
                var product = productForm.ID != 0 ? _ProductRepo.GetByID(productForm.ID) : new Product {
                    ID = productForm.ID
                };
                var passed = true;
                try {
                    var p = productForm.ToModel(product, ViewBag.Categories);
                    _ProductRepo.Update(p);
                }
                catch (System.FormatException) {
                    ViewBag.Alert = "Couldn't parse";
                    passed        = false;
                }

                if (passed)
                {
                    _ProductRepo.Save();
                    ViewBag.Alert = "Saved!";
                    productForm   = ProductForm.FromModel(product);
                }
            }

            if (Request.Form.Files["product-image"] != null && productForm.ID != 0)
            {
                var product = _ProductRepo.GetByID(productForm.ID);
                var image   = new Image {
                    ContentType = Request.Form.Files["product-image"].ContentType,
                    Data        = new byte[Request.Form.Files["product-image"].Length]
                };

                Request.Form.Files["product-image"].OpenReadStream().Read(image.Data, 0, image.Data.Length);

                var pi = new ProductImage {
                    Image = image, Product = product
                };
                if (product.ProductImages is null)
                {
                    product.ProductImages    = new List <ProductImage>();
                    product.MainProductImage = pi;
                }

                product.ProductImages.Add(pi);

                _ProductRepo.Update(product);
                _ProductRepo.Save();
                ViewBag.Message = "Image added!";
            }

            if (zeroId && ModelState.IsValid)
            {
                return(RedirectToAction("Product", new { productForm.ID }));
            }

            return(View("Product", productForm));
        }