public ActionResult Create(NewProductViewModel model) { if (ModelState.IsValid) { try { var product = productService.CreateNewProduct(model); Success(string.Format("Product '{0}' was added.", product.Name)); return RedirectToAction("Index"); } catch (Exception e) { Error(e.Message); return View(model); } } return View(model); }
public ProductViewModel CreateNewProduct(NewProductViewModel model) { var product = Mapper.Map<NewProductViewModel, Product>(model); #region Categories if (model.CategoryIds != null) { var foundCategories = (from category in context.Categories from categoryId in model.CategoryIds where category.Id == categoryId select category).ToList(); product.Categories = foundCategories; } #endregion context.Products.Add(product); context.SaveChanges(); #region Images if (model.Files != null) { var httpPostedFileBases = model.Files; AddImages(httpPostedFileBases, product); if (!product.ProductImages.Any(image => image.Primary)) { product.ProductImages.First().Primary = true; } } #endregion context.SaveChanges(); return Mapper.Map<ProductViewModel>(product); }