public ActionResult Create(FormCollection fc, Product product) { if (this.ModelState.IsValid) { if (product.Name == null) { product.Name = string.Empty; } if (product.Description == null) { product.Description = string.Empty; } foreach (string field in fc) { if (field.StartsWith("category")) { var catId = int.Parse(fc[field]); var cat = this.db.Categories.Find(catId); product.Categories.Add(cat); } } this.db.Products.Add(product); this.db.SaveChanges(); return this.RedirectToAction("Index"); } this.ViewBag.categoriesSelectTemplate = new SelectList(this.db.Categories, "CategoryId", "Name"); return this.View(product); }
public ActionResult Edit(FormCollection fc, Product product) { ////try ////{ if (this.ModelState.IsValid) { // Copy values var realProduct = this.db.Products.Find(product.ProductId); realProduct.Name = product.Name ?? string.Empty; realProduct.Description = product.Description ?? string.Empty; realProduct.ImageUrl = product.ImageUrl; realProduct.Price = product.Price; realProduct.IsFeatured = product.IsFeatured; realProduct.IsPublished = product.IsPublished; // Categories realProduct.Categories.Clear(); foreach (string field in fc) { if (field.StartsWith("category")) { var catId = int.Parse(fc[field]); var cat = this.db.Categories.Find(catId); realProduct.Categories.Add(cat); } } this.db.SaveChanges(); return this.RedirectToAction("Index"); } ////} ////catch (Exception ex) ////{ //// ViewBag.Error = ex; //// throw; ////} this.ViewBag.categoriesSelectTemplate = new SelectList(this.db.Categories, "CategoryId", "Name"); this.ViewBag.CategoriesIds = string.Join(",", product.Categories.Select(c => c.CategoryId)); return this.View(product); }