public ActionResult Add(AddProductBm bm, HttpPostedFileBase image) { if (!this.ModelState.IsValid) { return(this.View(bm)); } try { string imagePath = ""; if (image != null) { var allowedTypes = new[] { "image/jpeg", "image/jpg", "image/png" }; if (allowedTypes.Contains(image.ContentType)) { var imagesPath = "/Content/Images/"; var fileName = image.FileName; var uploadPath = imagesPath + fileName; var psihicalPath = Server.MapPath(uploadPath); image.SaveAs(psihicalPath); bm.ImageUrl = uploadPath; } } this.service.AddProduct(bm); return(RedirectToAction("all")); } catch (DbEntityValidationException ex) { var error = ex.EntityValidationErrors.First().ValidationErrors.First(); this.ModelState.AddModelError(error.PropertyName, error.ErrorMessage); IEnumerable <AllCategoriesVm> categories = this.service.GetAllCategoriesTitles(); AddProcuctVm vm = new AddProcuctVm() { Categories = categories }; return(View(vm)); } }
public void AddProduct(AddProductBm bm) { Product model = new Product { Description = bm.Description, Category = this.Context.Categories.FirstOrDefault(c => c.Title == bm.Category), ImageUrl = bm.ImageUrl, Model = bm.Model, Price = bm.Price, Quantity = bm.Quantity, Title = bm.Title }; try { this.Context.Products.Add(model); this.Context.SaveChanges(); } catch (Exception) { throw; } }