Ejemplo n.º 1
0
        public ActionResult LoadProductPage()
        {
            /*viewbag does not pass data from controller to view
             * tempdata store the values in session state so that it can
             * be used again...viewbag and viewdata do not
             *
             */
            // ViewBag.Colors = Getsizes();
            ProductVM productVM = new ViewModels.ProductVM();

            productVM.Styles = GetStyles();
            return(View("ProductEntry", productVM));
        }
        public async Task <IActionResult> Create([Bind("ID,Name,Description,Price,Shipping,ImageUpload,Category")] ViewModels.ProductVM product)
        {
            // validate image upload
            if (product.ImageUpload == null || product.ImageUpload.Length == 0)
            {
                ModelState.AddModelError("ImageUpload", "This field is required");
            }
            else if (!validImageTypes.Contains(product.ImageUpload.ContentType))
            {
                ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
            }

            if (ModelState.IsValid)
            {
                // Copy ViewModel info to Model
                var newProduct = new Product()
                {
                    ID          = product.ID,
                    Name        = product.Name,
                    Description = product.Description,
                    Price       = product.Price,
                    Shipping    = product.Shipping,
                    Category    = product.Category
                };

                // Save image to disk and store filepath in model
                if (product.ImageUpload != null && product.ImageUpload.Length != 0)
                {
                    var imageDir  = "/images";
                    var imagePath = Path.Combine(_env.WebRootPath, "images", product.ImageUpload.FileName);
                    //var imageUrl = Path.Combine(imageDir, product.ImageUpload.FileName);
                    var imageUrl = imageDir + "/" + product.ImageUpload.FileName;
                    product.ImageUpload.CopyTo(new FileStream(imagePath, FileMode.Create));
                    newProduct.ImageURL = imageUrl;
                }

                _context.Add(newProduct);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(product));
        }