public async Task <IActionResult> RemoveFromPantry(AddPantryItemViewModel VM, int[] pantryIds) { // used checkboxes, looping through list of cheeseIds foreach (int pantryId in pantryIds) { // accessing the existing cheese object GroceryItem theItem = Context.GroceryItems.Single(c => c.ID == pantryId); // checking if the user is allowed to delete items from the pantry var isAuthorized = await AuthorizationService.AuthorizeAsync( User, theItem, FoodOperations.Delete); if (!isAuthorized.Succeeded) { return(Forbid()); } // removing each cheese in the list from the database Context.GroceryItems.Remove(theItem); } // saving changes to the database await Context.SaveChangesAsync(); // redirecting back to the index to show pantry return(Redirect("/Pantry")); }
// GET: /<controller>/ public IActionResult Index() { var currentUserId = UserManager.GetUserId(User); // creating viewmodel for forms and pantry list AddPantryItemViewModel viewModel = new AddPantryItemViewModel(Context.Locations.ToList()); viewModel.PantryList = Context.GroceryItems.Where(g => g.IsInPantry == true).Where(p => p.UserID == currentUserId).ToList(); return(View(viewModel)); }
public async Task <IActionResult> AddToPantry(AddPantryItemViewModel viewModel) { // getting user var currentUserId = UserManager.GetUserId(User); // checking if model is valid if (ModelState.IsValid) { //creating new pantry item for list GroceryItem newPantryItem = new GroceryItem() { Name = viewModel.Name, GroceryNote = viewModel.GroceryNote, IsInPantry = true, LocationID = viewModel.GroceryItemLocationID, UserID = currentUserId }; //checking if the user has access to create a pantry item var isAuthorized = await AuthorizationService.AuthorizeAsync (User, newPantryItem, FoodOperations.Create); if (!isAuthorized.Succeeded) { return(Forbid()); } // adding and updating database with object Context.GroceryItems.Add(newPantryItem); await Context.SaveChangesAsync(); return(Redirect("/Pantry")); } AddPantryItemViewModel newAddViewModel = new AddPantryItemViewModel(Context.Locations.ToList()); viewModel.PantryList = Context.GroceryItems.Where(g => g.IsInPantry == true).Where(p => p.UserID == currentUserId).ToList(); return(View("Index", newAddViewModel)); }