// Start a topic test. public async Task <ActionResult> TopicTest(int?id) { try { // I.Checks. // Check id. if (!int.TryParse(id.ToString(), out int intId)) { return(RedirectToAction("Index")); } // Get courseDTO object. TopicDTO topicDTO = await TopicService.GetAsync(intId); if (topicDTO == null) { return(RedirectToAction("Index")); } //Get courseDTO object. CourseDTO courseDTO = await CourseService.GetAsync(topicDTO.CourseId); if (courseDTO == null) { return(RedirectToAction("Index")); } // II. Set ViewBag properties. ViewBag.CourseName = courseDTO.CourseTitle; ViewBag.TopicName = topicDTO.TopicTitle; ViewBag.TopicId = intId; // III. AutoMapper Setup. var config = new MapperConfiguration(cfg => { cfg.CreateMap <QuestionDTO, UserQuestionAnswersViewModel>() .ForMember("Question", opt => opt.MapFrom(obj => obj.QuestionText)) .ForMember("AnswerType", opt => opt.MapFrom(obj => obj.AnswerType.AnswerTypeDescription)) .ForMember("AvailableUserAnswers", opt => opt.MapFrom(obj => obj.Answers)) .ForMember("QuestionWeight", opt => opt.MapFrom(obj => obj.QuestionWeight)) .ForMember(q => q.SelectedUserAnswers, option => option.Ignore()) .ForMember(q => q.PostedUserAnswers, option => option.Ignore()); cfg.CreateMap <AnswerDTO, UserAnswer>() .ForMember("Id", opt => opt.MapFrom(obj => obj.AnswerId)) .ForMember("Answer", opt => opt.MapFrom(obj => obj.AnswerText)) .ForMember("IsSelected", opt => opt.MapFrom(obj => obj.IsProper)); }); IMapper iMapper = config.CreateMapper(); // IV. Get data for a view. IList <QuestionDTO> source = await TestingService.GetRandomQuestionsForTopic(intId); IEnumerable <UserQuestionAnswersViewModel> topicTestQuestionList = iMapper.Map <IEnumerable <QuestionDTO>, IEnumerable <UserQuestionAnswersViewModel> >(source); // V. Set properties: TestQuetions, AllAnswers and UserAnswers. TestQuetions = topicTestQuestionList.ToList(); AllAnswers.Clear(); UserAnswers.Clear(); foreach (var item in topicTestQuestionList) { AllAnswers[item.QuestionId] = item.AvailableUserAnswers.ToList(); UserAnswers[item.QuestionId] = new List <UserAnswer>(); } // VI. Set Timer. TestPeriod = courseDTO.TimeToAnswerOneQuestion * topicTestQuestionList.Count(); StartTestTime = DateTime.Now; // VII. return(View(topicTestQuestionList)); } catch (Exception ex) { throw new Exception(ex.Message); } }