public async Task <IActionResult> Create(CreateGiftListViewModel viewModel) { var user = await GetCurrentUserAsync(); viewModel.ListTypes = await _context.ListTypes.ToListAsync(); if (viewModel.GiftList.ReceiverId == null) { // if the user has not selected a receiver, get the possible receivers and listTypes from the db to use for the select lists viewModel.Receivers = await _context.ApplicationUsers .Include(u => u.GroupUsers) .Where(u => u.Id != user.Id) // filter to include users who share a group with the logged in user .Where(u => u.GroupUsers .Any(gu => gu.Group.GroupUsers .Any(gu => gu.UserId == user.Id))) .ToListAsync(); var errorMsg = TempData["ErrorMessage"] as string; TempData["ErrorMessage"] = "Please select a receiver for this gift list"; return(View(viewModel)); } ModelState.Remove("GiftList.CreatorId"); if (ModelState.IsValid) { viewModel.GiftList.CreatorId = user.Id; // Check if the user selected "other" for the receiver if (viewModel.GiftList.ReceiverId == "0") { // Have the user enter a name for the receiver if (viewModel.GiftList.ReceiverName == null) { return(View(viewModel)); } // remove the receiver id of "0" so that the gift list can be entered into the db with a receiver id as null and a receiver name included viewModel.GiftList.ReceiverId = null; } // add gift list to the db _context.Add(viewModel.GiftList); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } // if model state is not valid, get the possible receivers and listTypes from the db to use for the select lists viewModel.Receivers = await _context.ApplicationUsers .Include(u => u.GroupUsers) .Where(u => u.Id != user.Id) // filter to include users who share a group with the logged in user .Where(u => u.GroupUsers .Any(gu => gu.Group.GroupUsers .Any(gu => gu.UserId == user.Id))) .ToListAsync(); return(View(viewModel)); }
// GET: GiftLists/Create public async Task <IActionResult> Create() { var user = await GetCurrentUserAsync(); var viewModel = new CreateGiftListViewModel { Receivers = await _context.ApplicationUsers .Include(u => u.GroupUsers) .Where(u => u.Id != user.Id) // filter to include users who share a group with the logged in user .Where(u => u.GroupUsers .Any(gu => gu.Group.GroupUsers .Any(gu => gu.UserId == user.Id))) .ToListAsync(), ListTypes = await _context.ListTypes.ToListAsync() }; return(View(viewModel)); }