public async Task <IActionResult> Test(TestBigModel model) { int courseId = model.TestQuestions.FirstOrDefault().Question.CourseId; int totalQuestions = model.TestQuestions.Count(); int totalTrueAnswers = 0; foreach (var item in model.TestQuestions) { int trueAnswer = await _context.Answer.Where(x => x.QuestionId == item.Question.Id && x.Verity == true).Select(x => x.Id).FirstOrDefaultAsync(); if (item.Question.SelectedAnswer == trueAnswer) { totalTrueAnswers = totalTrueAnswers + 1; } } double percent = ((double)totalTrueAnswers / totalQuestions) * 100; TestResult testResultModel = new TestResult(); testResultModel.CourseId = courseId; testResultModel.Percent = percent; //zobrazeni vysledku testu CourseUser courseToAddResult = await _context.CourseUser.Where(x => x.CourseId == courseId).FirstOrDefaultAsync(); courseToAddResult.ResultPercent = percent; courseToAddResult.NumberOfTests = courseToAddResult.NumberOfTests + 1; _context.Update(courseToAddResult); await _context.SaveChangesAsync(); if (percent >= 80) { courseToAddResult.Finished = true; _context.Update(courseToAddResult); await _context.SaveChangesAsync(); return(View("TestSuccess", testResultModel)); } return(View("TestFailure", testResultModel)); }
// GET: Tests/Edit/5 public async Task <IActionResult> Test(int?id) { Random random = new Random(); TestBigModel model = new TestBigModel(); List <Question> AllQuestions = await _context.Question.Include(x => x.Answers).Where(x => x.Course.Id == id).ToListAsync(); //Všechny otázky, které náleží danému kurzu includujeme také answers List <TestQuestion> testQuestions = new List <TestQuestion>(); //Vytvoříme si zatím prázdný list Test Questions a později ho otázku po otázce inicializujeme for (int i = 0; i < AllQuestions.Count; i++) //Pro každou z otázek, které se nachází v Listu AllQuestions { TestQuestion testQuestion = new TestQuestion(); //Dočasý objekt TestQuestion existující pouze ve scope tohoto foreach loopu (při každém scope se vytváří znovu a znovu, dá se říct že se resetuje) testQuestion.Question = AllQuestions[i]; testQuestion.Answers = AllQuestions[i].Answers.ToList(); testQuestion.Answers.Shuffle(); testQuestions.Add(testQuestion); //Nakonec po inicializaci všech vlastností vložíme dočasný objekt do listu testQuestions } model.TestQuestions = testQuestions; model.TestQuestions.Shuffle(); return(View(model)); //Nakonec list odesíláme do View jako model }