public async Task <IActionResult> Create(CategoriesAndSubCategoriesViewModel model) { if (ModelState.IsValid) { var doesSubCategoryExists = _db.SubCategory.Include(s => s.Category).Where(s => s.Name == model.SubCategory.Name && s.Category.Id == model.SubCategory.CategoryId); if (doesSubCategoryExists.Count() > 0) { //Error StatusMessage = "Error: Sub Category exists under " + doesSubCategoryExists.First().Category.Name + " category. Please use another name."; } else { _db.SubCategory.Add(model.SubCategory); await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } CategoriesAndSubCategoriesViewModel modelVM = new CategoriesAndSubCategoriesViewModel() { CategoriesList = await _db.Category.ToListAsync(), SubCategory = model.SubCategory, SubCategoriesList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).ToListAsync(), StatusMessage = StatusMessage }; return(View(modelVM)); }
// GET - Create public async Task <IActionResult> Create() { CategoriesAndSubCategoriesViewModel model = new CategoriesAndSubCategoriesViewModel() { CategoriesList = await _db.Category.ToListAsync(), SubCategory = new SubCategory(), SubCategoriesList = await _db.SubCategory.OrderBy(s => s.Name).Select(s => s.Name).Distinct().ToListAsync(), }; return(View(model)); }
// GET - Edit public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var subCategory = await _db.SubCategory.SingleOrDefaultAsync(s => s.Id == id); if (subCategory == null) { return(NotFound()); } CategoriesAndSubCategoriesViewModel model = new CategoriesAndSubCategoriesViewModel() { CategoriesList = await _db.Category.ToListAsync(), SubCategory = subCategory, SubCategoriesList = await _db.SubCategory.OrderBy(s => s.Name).Select(s => s.Name).Distinct().ToListAsync(), }; return(View(model)); }