public async Task <IActionResult> Create(SubCategoryAndViewModel 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))); } } SubCategoryAndViewModel modelVM = new SubCategoryAndViewModel() { 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)); }
public async Task <IActionResult> Edit(int id, SubCategoryAndViewModel 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 { var subCatFromDb = await _db.SubCategory.FindAsync(model.SubCategory.Id); subCatFromDb.Name = model.SubCategory.Name;//updating one property of row await _db.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } } SubCategoryAndViewModel modelVM = new SubCategoryAndViewModel() { CategoryList = await _db.Category.ToListAsync(), SubCategory = model.SubCategory, SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(p => p.Name).ToListAsync(), StatusMessage = StatusMessage }; // modelVM.SubCategory.Id = id; return(View(modelVM)); }
//GET - Create public async Task <IActionResult> Create() { SubCategoryAndViewModel model = new SubCategoryAndViewModel() { CategoryList = await _db.Category.ToListAsync(), SubCategory = new Models.SubCategory(), SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(prop => prop.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()); } SubCategoryAndViewModel model = new SubCategoryAndViewModel() { CategoryList = await _db.Category.ToListAsync(), SubCategory = subCategory, SubCategoryList = await _db.SubCategory.OrderBy(p => p.Name).Select(prop => prop.Name).Distinct().ToListAsync() }; return(View(model)); }