// GET: Sections/Problems/5 public async Task <IActionResult> Problems(int?id) { if (id == null) { return(NotFound()); } var section = await _context.Sections .Include(s => s.ProblemSet) .FirstOrDefaultAsync(m => m.ID == id); if (section == null) { return(NotFound()); } var pvmList = new List <ProblemVM>(); foreach (var problem in section.ProblemSet) { var pvm = new ProblemVM { Problem = problem, ID = problem.ID, CorrectAnswer = problem.CorrectChoiceID, Score = problem.Score }; pvmList.Add(pvm); } var vm = new ProblemPageVM { SectionID = Convert.ToInt32(id), Problems = pvmList }; return(View(vm)); }
public async Task <IActionResult> Problems(ProblemPageVM vm) { var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); var currentUser = await _context.Users.FirstOrDefaultAsync(u => u.Id == userId); int score = 0; int historyScore = 0; int correctCount = 0; foreach (var problem in vm.Problems) { if (problem.SelectedAnswer == null) { continue; } if (problem.SelectedAnswer == problem.CorrectAnswer) { score += problem.Score; correctCount++; } } var history = await _context.UserScoreHistories .FirstOrDefaultAsync(u => u.SectionID == vm.SectionID && u.UserId == userId); if (history == null) { _context.UserScoreHistories.Add(new UserScoreHistory { UserId = userId, SectionID = vm.SectionID, HighScore = score }); currentUser.Score += score; } else { historyScore = history.HighScore; history.HighScore = Math.Max(historyScore, score); _context.Update(history); currentUser.Score += (score > historyScore) ? (score - historyScore) : 0; } await _context.SaveChangesAsync(); return(RedirectToAction("Result", new { score = score, historyScore = historyScore, correctCount = correctCount, sectionID = vm.SectionID })); }