public ActionResult Create(FormCollection fc, Category shopcategory) { if (this.ModelState.IsValid) { int newParentCategoryId; var newParentCategory = int.TryParse(fc["NewParentCategoryId"], out newParentCategoryId) ? this.db.Categories.Find(newParentCategoryId) : null; if (newParentCategory != null) { shopcategory.ParentCategory = newParentCategory; } this.db.Categories.Add(shopcategory); this.db.SaveChanges(); return this.RedirectToAction("Index"); } this.ViewBag.CategorySelectList = this.GetCategorySelectList(shopcategory); return this.View(shopcategory); }
public ActionResult Edit(FormCollection fc, Category shopcategory) { if (this.ModelState.IsValid) { var origShopCategory = this.db.Categories.Find(shopcategory.CategoryId); origShopCategory.Name = shopcategory.Name; origShopCategory.Description = shopcategory.Description; int newParentCategoryId; var newParentCategory = int.TryParse(fc["NewParentCategoryId"], out newParentCategoryId) ? this.db.Categories.Find(newParentCategoryId) : null; if (newParentCategory == null) { if (origShopCategory.ParentCategory != null) { origShopCategory.ParentCategory.Subcategories.Remove(origShopCategory); } } else { origShopCategory.ParentCategory = newParentCategory; } this.db.SaveChanges(); return this.RedirectToAction("Index"); } this.ViewBag.CategorySelectList = this.GetCategorySelectList(shopcategory); return this.View(shopcategory); }
private SelectList GetCategorySelectList(Category category = null) { var parentCategoryId = category == null ? null : (category.ParentCategory == null ? null : (int?)category.ParentCategory.CategoryId); return new SelectList( this.db.Categories, "CategoryId", "Name", parentCategoryId); }