public async Task <IActionResult> EnrollStudents(int?id) { if (id == null) { return(NotFound()); } var course = _context.Course.Where(c => c.Id == id).Include(c => c.FirstTeacher).Include(c => c.SecondTeacher) .Include(c => c.Students).ThenInclude(c => c.Student).First(); if (course == null) { return(NotFound()); } CoursesEnrollStudentsClass viewmodel = new CoursesEnrollStudentsClass { Course = course, StudentList = new MultiSelectList(_context.Student.OrderBy(s => s.FirstName), "Id", "FirstName"), SelectedStudents = course.Students.Select(s => s.StudentId) }; ViewData["FirstTeacherId"] = new SelectList(_context.Set <Teacher>(), "Id", "FirstName", viewmodel.Course.FirstTeacherId); ViewData["SecondTeacherId"] = new SelectList(_context.Set <Teacher>(), "Id", "FirstName", viewmodel.Course.SecondTeacherId); return(View(viewmodel)); }
public async Task <IActionResult> EnrollStudents(int id, int inputYear, string inputSemester, CoursesEnrollStudentsClass viewmodel) { if (id != viewmodel.Course.Id) { return(NotFound()); } if (ModelState.IsValid) { try { await _context.SaveChangesAsync(); IEnumerable <int> listStudents = viewmodel.SelectedStudents; IQueryable <Enrollment> toBeRemoved = _context.Enrollment.Where(s => !listStudents.Contains(s.StudentId) && s.CourseId == id).Include(s => s.Course).Include(s => s.Student); _context.Enrollment.RemoveRange(toBeRemoved); IEnumerable <int> existStudents = _context.Enrollment.Where(s => listStudents.Contains(s.StudentId) && s.CourseId == id).Include(s => s.Course).Include(s => s.Student) .Select(s => s.StudentId); IEnumerable <int> newStudents = listStudents.Where(s => !existStudents.Contains(s)); foreach (int studentId in newStudents) { _context.Enrollment.Add(new Enrollment { StudentId = studentId, CourseId = id, Year = inputYear, Semester = inputSemester }); } _context.Update(viewmodel.Course); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CourseExists(viewmodel.Course.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["FirstTeacherId"] = new SelectList(_context.Set <Teacher>(), "Id", "FirstName", viewmodel.Course.FirstTeacherId); ViewData["SecondTeacherId"] = new SelectList(_context.Set <Teacher>(), "Id", "FirstName", viewmodel.Course.SecondTeacherId); return(View(viewmodel)); }