public async Task <IActionResult> Create(SubCatgoryAndCategoryViewModel model) { if (ModelState.IsValid) { var doesSubcatExists = _db.SubCategory.Include(s => s.Category).Where(s => s.Name == model.SubCategory.Name && s.Category.Id == model.SubCategory.CategoryId); if (doesSubcatExists.Count() > 0) { //Error StatusMessage = "Error : Sub-category already exists under, " + doesSubcatExists.First().Category.Name + " category. Please use another name."; } else { _db.SubCategory.Add(model.SubCategory); await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } SubCatgoryAndCategoryViewModel modelVM = new SubCatgoryAndCategoryViewModel { CategoryList = await _db.Category.ToListAsync(), SubCategory = model.SubCategory, SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).ToListAsync(), StatusMessage = StatusMessage }; return(View(modelVM)); }
// GET - Create public async Task <IActionResult> Create() { SubCatgoryAndCategoryViewModel model = new SubCatgoryAndCategoryViewModel() { CategoryList = await _db.Category.ToListAsync(), SubCategory = new Models.SubCategory(), SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.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(m => m.Id == id); if (subCategory == null) { return(NotFound()); } SubCatgoryAndCategoryViewModel model = new SubCatgoryAndCategoryViewModel() { CategoryList = await _db.Category.ToListAsync(), SubCategory = subCategory, SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).Distinct().ToListAsync() }; return(View(model)); }
public async Task <IActionResult> Edit(SubCatgoryAndCategoryViewModel model) { if (ModelState.IsValid) { var doesSubcatExists = _db.SubCategory.Include(s => s.Category).Where(s => s.Name == model.SubCategory.Name && s.Category.Id == model.SubCategory.CategoryId); if (doesSubcatExists.Count() > 0) { //Error StatusMessage = "Error : Sub-category already exists under, " + doesSubcatExists.First().Category.Name + " category. Please use another name."; } else { var subCatFromDb = await _db.SubCategory.FindAsync(model.SubCategory.Id); subCatFromDb.Name = model.SubCategory.Name; await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } SubCatgoryAndCategoryViewModel modelVM = new SubCatgoryAndCategoryViewModel { CategoryList = await _db.Category.ToListAsync(), SubCategory = model.SubCategory, SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).ToListAsync(), StatusMessage = StatusMessage }; //To parse the category Id even after the error message of redundant //Sub-category name is hit and // a different value is entered before a page refresh //modelVM.SubCategory.Id = id; return(View(modelVM)); }