예제 #1
0
        public ProductViewModel EditProduct(int id, EditProductViewModel model)
        {
            var product = context.Products.Find(id);

            Mapper.Map(model, product);

            #region Category

            if (model.CategoryIds != null)
            {
                foreach (int categoryId in model.CategoryIds)
                {
                    Category category = context.Categories.Find(categoryId);

                    if (category == null)
                        continue;

                    if (product.Categories.Any(c => c.Id == categoryId))
                        continue;

                    product.Categories.Add(category);
                }

                foreach (Category category in product.Categories)
                {
                    if (model.CategoryIds.All(i => i != category.Id))
                    {
                        product.Categories.Remove(category);
                    }
                }
            }

            #endregion

            #region Images

            if (model.Files != null)
            {
                var httpPostedFileBases = model.Files;
                AddImages(httpPostedFileBases, product);
            }

            var images = (from image in model.Images
                          from productImage in product.ProductImages
                          where productImage.Id == image.Id && image.Delete
                          select productImage).ToList();

            foreach (var productImage in images)
            {
                try
                {
                    product.ProductImages.Remove(productImage);
                    File.Delete(productImage.Path);
                }
                catch (DirectoryNotFoundException e)
                {

                }
            }

            product.ProductImages.Single(image => image.Id == model.SelectedDefaultImage).Primary = true;

            #endregion

            context.SaveChanges();

            return Mapper.Map<ProductViewModel>(product);
        }
예제 #2
0
 public ActionResult Edit(int id, EditProductViewModel model)
 {
     if (ModelState.IsValid)
     {
         try
         {
             var product = productService.EditProduct(id, model);
             Success(string.Format("Product '{0}' was successfully updated.", product.Name));
             return RedirectToAction("Index");
         }
         catch (Exception e)
         {
             Error(e.Message);
             return View(model);
         }
     }
     return View(model);
 }