public ActionResult EditProduct(Product model) { if (!ModelState.IsValid) { return View(); } if (model.Id == 0) { try { context.Product.Add(model); context.SaveChanges(); } catch (Exception ex) { ModelState.AddModelError("DbError", ex.Message); } } else { var old = context.Product.SingleOrDefault(t => t.Id == model.Id); old.Name = model.Name; old.CategoryId = model.CategoryId; old.SubCategory = model.SubCategory; old.Color = model.Color; old.ImgUrl = model.ImgUrl; old.ThumbnailUrl = model.ThumbnailUrl; context.SaveChanges(); } return RedirectToAction("Product"); }
public ActionResult EditProduct(int? id) { var m = new Product(); if (id.HasValue) { var old = context.Product.SingleOrDefault(t => t.Id == id.Value); m = old ?? m; } m.CategoryList = context.ProductCategory.Where(t => t.ParentId == null); var selCateList = new List<SelectListItem>(); context.ProductCategory.Where(t => t.ParentId == null) .ForEach(t => selCateList.Add(new SelectListItem(){ Text = t.Name, Value = t.Id.ToString() }) ); ViewData["catlist"] = selCateList; return View(m); }