public ActionResult Edit(Product product) { var productDb = DbContext.Products.Find(product.ProductId); if (productDb == null) { ModelState.AddModelError(string.Empty, "Không thể lưu thay đổi, sản phẩm này đã bị xóa"); } if (ModelState.IsValid) { try { TryUpdateModel(productDb); DbContext.Entry(productDb).State = EntityState.Modified; if (DbContext.SaveChanges() > 0) { return Redirect(null); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); ex.Write(LogPath); } } InitFormData(product); return View(product); }
public ActionResult Create(Product product) { try { if (ModelState.IsValid) { DbContext.Products.Add(product); if (DbContext.SaveChanges() > 0) return Redirect(null); ModelState.AddModelError("", "Đã có lỗi xảy ra. Vui lòng thử lại sau."); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); ex.Write(LogPath); } InitFormData(product); return View(product); }
public ActionResult Create() { var product = new Product() {Actived = true}; InitFormData(product); return View(product); }
private void InitFormData(Product product) { //Lấy tất cả các nhóm câu hỏi và gom nhóm chúng var categories = DbContext.Categories.Where(s => s.Actived).ToList(); var suppliers = DbContext.Suppliers.ToList(); //Tạo danh sách chọn làm dữ liệu nguồn cho DropDownList ViewBag.CategoryId = product.CategoryId > 0 ? new SelectList(categories, "CategoryId", "CategoryName", product.CategoryId) : new SelectList(categories, "CategoryId", "CategoryName", null); ViewBag.SupplierId = product.SupplierId > 0 ? new SelectList(suppliers, "SupplierId", "SupplierName", product.SupplierId) : new SelectList(suppliers, "SupplierId", "SupplierName", null); }