Пример #1
0
        [ValidateAntiForgeryToken] // step 22b: 
        public ActionResult Create(QuizFormViewModel viewModel) // takes parameter of QuizFormViewModel -- the model behind the view. When posting the form will result this action
        {
            if (!ModelState.IsValid)
            {
                viewModel.Genres = _context.Genres.ToList();
                return View("QuizForm", viewModel);
            }

            var userId = User.Identity.GetUserId();   // need to set the authorId, need an applicationUser object
            //var author = _context.Users.Single(u => u.Id == userId); // accessing when not using FK
            //var genre = _context.Genres.Single(g => g.Id == viewModel.Genre); // accessing when not using FK

            // step 13c: creating new Quiz object and converting it to the viewModel object
            var quiz = new Quiz
            {
                // need to set the authorId, need an applicationUser object
                // Author = author,
                Creation = viewModel.GetDateTime(),
                //  Genre = genre,
                Title = viewModel.Title,
                Description = viewModel.Description,

                // step 14: Modified by adding the FK for Author and Genre. the above are uncommented.
                AuthorId = userId,
                GenreId = viewModel.Genre
            };

            // adding the object to the contex to be tracked by EF
            // Ef will generate a sql statment and execute it against the database.
            _context.Guizzes.Add(quiz);
            _context.SaveChanges();

            return RedirectToAction("QuizsIndex", "Home"); // redirecting the user to the homepage --> later to the list of all the upcoming quizzes
        }