Beispiel #1
0
        public async Task <IActionResult> EditMultiChoiceQuestion(int testId, int questionId,
                                                                  [FromBody] AddMultiChoiceQuestionViewModel 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.MultiChoiceQuestions
                           .AsNoTracking()
                           .FirstOrDefaultAsync(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.MultiChoiceQuestions.Add(question);
                    await _context.SaveChangesAsync();

                    var questionCopyId = question.Id;

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

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

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

                    questionCopy.Title = model.Title;
                    questionCopy.Score = model.Score;
                    _context.MultiChoiceQuestions.Update(questionCopy);

                    UpdateQuestionOptions(model.Options, questionCopyId);

                    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));
        }
Beispiel #2
0
        public async Task <IActionResult> AddMultiChoiceQuestion([FromBody] AddMultiChoiceQuestionViewModel 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 MultiChoiceQuestion
                    {
                        Title        = model.Title,
                        QuestionType = Enum.GetName(typeof(Question.QuestionTypeEnum), 2),
                        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;
                    }

                    // обновить вопрос и применить изменения
                    _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));
        }