public async Task <IActionResult> ChallengeSelect(FieldSelectViewModel fieldSelectViewModel) { if (!ModelState.IsValid) { return(View(await GetCurrentFieldSelectViewModel())); } User user = await _userManager.FindByNameAsync(User.Identity.Name); var userFieldsToDelete = _context.UserFields.Where(u => u.UserId == user.Id).ToList(); foreach (var userFieldToDelete in userFieldsToDelete) { _context.UserFields.Remove(userFieldToDelete); } await _context.SaveChangesAsync(); foreach (var fieldID in fieldSelectViewModel.SelectedFields) { _context.UserFields.Add(new UserField { FieldId = fieldID, UserId = user.Id }); } await _context.SaveChangesAsync(); return(RedirectToAction("ReadinessCheck", "Home")); }
private async Task <FieldSelectViewModel> GetCurrentFieldSelectViewModel() { User user = await _userManager.FindByNameAsync(User.Identity.Name); var fields = _context.UserFields.Where(u => u.UserId == user.Id).ToList(); FieldSelectViewModel fieldSelectViewModel = new FieldSelectViewModel(); fieldSelectViewModel.SelectedFields = new List <int>(); foreach (var field in fields) { (fieldSelectViewModel.SelectedFields as List <int>).Add(field.FieldId); } return(fieldSelectViewModel); }