[HttpPost] public IActionResult SubmitTest(TestViewModel model) { // Check if the user has already passed the test bool hasPassed = HttpContext.Session.GetBool("TestPassed"); // If the user has already passed, redirect to the course page if (hasPassed) { return RedirectToAction("TakeCourse", "Courses"); } // Retrieve the module and questions from the database Module module = _context.Modules.FirstOrDefault(m => m.ID == model.ModuleID); List<Question> questions = GetQuestionsForModule(module); // Keep track of the user's score int score = 0; // Iterate over the questions and check the selected answers for (int i = 0; i < questions.Count; i++) { Question question = questions[i]; // Get the selected answer(s) for the current question int[] selectedAnswerIds = model.Answers .Where(a => a.QuestionID == question.Id) .Select(a => a.ID) .ToArray(); // Get the answer count for the current question int answerCount = GetAnswerCountForQuestion(question.Id); // Check if the question is a radio type if (question.QuestionType == QuestionType.RADIO) { // Retrieve the correct answer for the question Answer correctAnswer = question.Answers.FirstOrDefault(a => a.IsCorrectAnswer); // Check if the selected answer matches the correct answer if (correctAnswer != null && selectedAnswerIds.Length == 1 && correctAnswer.IsCorrectAnswer) { // Increase the score if the selected answer is correct score++; } } // Check if the question is a checkbox type else if (question.QuestionType == QuestionType.CHECKBOX) { // Retrieve the correct answers for the question List<Answer> correctAnswers = question.Answers.Where(a => a.IsCorrectAnswer).ToList(); // Check if all selected answers are correct and no incorrect answers are selected if (correctAnswers.Count == selectedAnswerIds.Length && selectedAnswerIds.All(id => correctAnswers.Any(a => a.ID == id && a.IsCorrectAnswer))) { // Increase the score if all selected answers are correct score++; } } } // Determine if the user passed or failed the test based on the score bool passed = score == questions.Count; // If the user passed, store the information in the session and redirect to the course page if (passed) { HttpContext.Session.SetBool("TestPassed", true); return RedirectToAction("TakeCourse", "Courses"); } else { // Redirect back to the test page with a failure message TempData["TestResult"] = "You failed the test."; return RedirectToAction("TakeTest", new { moduleId = model.ModuleID }); } }
TestViewModel model
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)