Пример #1
0
        public async Task <IActionResult> EditSingleChoiceQuestion(int testId, int questionId,
                                                                   [FromBody] AddSingleChoiceQuestionViewModel model)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            var test = await _context.Tests.SingleOrDefaultAsync(t => t.Id == (int)RouteData.Values["testId"]);

            if (test == null)
            {
                return(NotFound());
            }
            if (test.CreatedBy != user)
            {
                return(Forbid());
            }
            var question = await _context.SingleChoiceQuestions
                           .AsNoTracking()
                           .SingleAsync(q => q.Id == questionId);

            if (question.TestId != test.Id)
            {
                return(NotFound());
            }

            model.TestId = test.Id;
            TryValidateModel(model);

            if (ModelState.IsValid)
            {
                // транзакция
                using (var ts = _context.Database.BeginTransaction())
                {
                    // copy question
                    question.Id = 0;

                    _context.SingleChoiceQuestions.Add(question);
                    await _context.SaveChangesAsync();

                    var questionCopyId = question.Id;

                    // заархивировать
                    var questionOld = await _context.SingleChoiceQuestions
                                      .SingleAsync(q => q.Id == questionId);

                    questionOld.IsDeleted = true;
                    _context.SingleChoiceQuestions.Update(questionOld);
                    await _context.SaveChangesAsync();

                    UpdateQuestionOptions(model.Options, questionCopyId);
                    //обновить опшены и копию
                    var questionCopy = await _context.SingleChoiceQuestions
                                       .Include(q => q.Options)
                                       .SingleAsync(q => q.Id == questionCopyId);

                    questionCopy.Title       = model.Title;
                    questionCopy.Score       = model.Score;
                    questionCopy.RightAnswer = questionCopy.Options.Single(o => o.IsRight);
                    _context.SingleChoiceQuestions.Update(questionCopy);


                    await _context.SaveChangesAsync();

                    ts.Commit();
                }

                var redirectUrl = Url.Action("Details", "Test", new { id = test.Id });
                return(new JsonResult(redirectUrl));
            }

            var errors = new List <ModelError>();

            foreach (var modelState in ViewData.ModelState.Values)
            {
                foreach (var error in modelState.Errors)
                {
                    errors.Add(error);
                }
            }

            Response.StatusCode = StatusCodes.Status400BadRequest;
            return(new JsonResult(errors));
        }
Пример #2
0
        public async Task <IActionResult> AddSingleChoiceQuestion([FromBody] AddSingleChoiceQuestionViewModel model)
        {
            var user = await _userManager.GetUserAsync(HttpContext.User);

            var test = await _context.Tests.SingleOrDefaultAsync(t => t.Id == (int)RouteData.Values["testId"]);

            if (test == null)
            {
                return(NotFound());
            }

            if (test.CreatedBy != user)
            {
                return(Forbid());
            }

            model.TestId = test.Id;
            TryValidateModel(model);
            if (ModelState.IsValid)
            {
                // транзакция
                using (var ts = _context.Database.BeginTransaction())
                {
                    var question = new SingleChoiceQuestion
                    {
                        Title        = model.Title,
                        QuestionType = Enum.GetName(typeof(Question.QuestionTypeEnum), 1),
                        Test         = test,
                        Score        = model.Score
                    };
                    //создать в базе вопрос
                    var questionCreated = (await _context.AddAsync(question)).Entity;
                    await _context.SaveChangesAsync(); //применить изменения

                    foreach (var option in model.Options)
                    {
                        // добавить в базу Options
                        var optionCreated = (await _context.AddAsync(
                                                 new Option {
                            IsRight = option.IsRight, Text = option.Text, Question = questionCreated
                        }))
                                            .Entity;
                        //questionCreated.Options.Add(optionCreated);

                        if (optionCreated.IsRight)
                        {
                            questionCreated.RightAnswer = optionCreated;
                        }
                    }

                    // обновить вопрос и применить изменения
                    _context.Questions.Update(questionCreated);
                    await _context.SaveChangesAsync();

                    ts.Commit();
                }

                var redirectUrl = Url.Action("Details", "Test", new { id = test.Id });
                return(new JsonResult(redirectUrl));
            }

            var errors = new List <ModelError>();

            foreach (var modelState in ViewData.ModelState.Values)
            {
                foreach (var error in modelState.Errors)
                {
                    errors.Add(error);
                }
            }
            Response.StatusCode = StatusCodes.Status400BadRequest;
            return(new JsonResult(errors));
        }