Exemplo n.º 1
0
        public ActionResult Create([Bind(Include = "CategoryId,ProductName,ProductCode,Price,ProductDescription,ProductDetailsListViewModel")] ProductViewModel productViewModel, IEnumerable <HttpPostedFileBase> upload)
        {
            int categoryCount = db.ProductCategories.Count(c => c.CategoryId == productViewModel.CategoryId);

            if (categoryCount == 0)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, ErrorMessage.CategoryDoesNotExist));
            }
            if (ModelState.IsValid)
            {
                if (upload != null && upload.Any(u => u != null && u.ContentLength > 0))
                {
                    string validationError = ValidatePhotoUpload(upload);
                    if (validationError != null)
                    {
                        ModelState.AddModelError("ProductPhotos", validationError);
                        return(View(productViewModel));
                    }
                    Product product = productViewModel.CreateProduct();
                    foreach (HttpPostedFileBase photo in upload)
                    {
                        string photoNameWithTimeStamp = AppendTimeStamp(photo.FileName);
                        string path = Path.Combine(Server.MapPath("~/Images"), photoNameWithTimeStamp);
                        photo.SaveAs(path);
                        product.ProductPhotos.Add(new Photos(photoNameWithTimeStamp));
                    }
                    db.Products.Add(product);
                    db.SaveChanges();
                    return(RedirectToAction("Index", new { categoryId = product.CategoryId }));
                }
                ModelState.AddModelError("ProductPhotos", "Produkt musi zawierać co najmniej jedno zdjęcie");
            }
            return(View(productViewModel));
        }