public async Task <IActionResult> CreateNewCategory() { var categoryCreationVM = new CategoryCreationViewModel { ParentCategories = await _context.ResourceCategories.Where(c => c.Depth == 0).ToListAsync(), }; return(View(categoryCreationVM)); }
public async Task <IActionResult> CreateNewCategory( [Bind("ParentCategoryID", "IsNewParentCategory", "NewParentCategoryName", "NewSubcategoryName")] CategoryCreationViewModel categoryCreationViewModel) { try { if (ModelState.IsValid) { int topLevelCategoryId = categoryCreationViewModel.ParentCategoryID; if (categoryCreationViewModel.IsNewParentCategory) { //create a new top level category if (string.IsNullOrEmpty(categoryCreationViewModel.NewParentCategoryName)) { ModelState.AddModelError("", "New top-level category is unspecified"); } var categoryEntry = _context.Add(new ResourceCategory() { CategoryName = categoryCreationViewModel.NewParentCategoryName, Depth = 0, }); await _context.SaveChangesAsync(); //overwrite this if new toplevel category to be created. topLevelCategoryId = categoryEntry.Entity.ID; } _context.Add(new ResourceCategory() { Depth = 1, ParentCategoryID = topLevelCategoryId, CategoryName = categoryCreationViewModel.NewSubcategoryName }); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } catch (DbUpdateException) { ModelState.AddModelError("", "Unable to save changes. " + "Try again, and if the problem persists " + "see your system administrator."); } return(View()); }