public ICollection <string> ValidateProduct(CreateProductFormModel product) { var errors = new List <string>(); if (product.Name == null || product.Name.Length < ProductNameMinLength || product.Name.Length > DefaultMaxLength) { errors.Add($"Product '{product.Name}' must be between {ProductNameMinLength} and {DefaultMaxLength} characters long"); } if (product.Price < ProductMinPrice || product.Price > ProductMaxPrice) { errors.Add($"Price must be in range ({ProductMinPrice} - {ProductMaxPrice})"); } return(errors); }
public ActionResult Create(CreateProductFormModel model) { if (ModelState.IsValid) { var sp = new SANPHAM(); sp.MaSP = model.MaSP; sp.TenSP = model.TenSP; //sp.Anh = model.Anh; sp.MoTa = model.MoTa; sp.ChiTiet = model.ChiTiet; sp.SoLuong = model.SoLuong; sp.NgayDangSP = DateTime.Now; sp.MaDM = model.MaDM; //try //{ // sp.TopHot = DateTime.ParseExact(model.TopHot, "dd/MM/yyyy", null); //} //catch { } sp.MaDM = model.MaDM; if (model.ProductImage != null) { var fileName = model.ProductImage.FileName; var link = "/uploads/" + fileName; var real = Server.MapPath("~" + link); model.ProductImage.SaveAs(real); sp.Anh = link; } try { db.SANPHAMs.Add(sp); db.SaveChanges(); } catch (Exception ex) { ModelState.AddModelError("save_error", "Lỗi khi lưu" + ex.Message); return(View(model)); } return(RedirectToAction("Index", "Product")); } return(View(model)); }
public HttpResponse Create(CreateProductFormModel model) { var modelErrors = validator.ValidateProduct(model); if (modelErrors.Any()) { return(Error(modelErrors)); } var product = new Product { Name = model.Name, Price = model.Price, }; this.data.Products.Add(product); this.data.SaveChanges(); return(Redirect("/")); }
public ActionResult Create() { var model = new CreateProductFormModel(); return(View(model)); }