public async Task <IActionResult> Edit(int id, StudentCourseEdit model) { if (id != model.Student.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(model.Student); await _context.SaveChangesAsync(); IEnumerable <int> listCourses = model.SelectedCourses; IQueryable <Enrollment> toBeRemoved = _context.Enrollment.Where(s => !listCourses.Contains(s.CourseId) && s.StudentId == id); _context.Enrollment.RemoveRange(toBeRemoved); IEnumerable <int> existCourses = _context.Enrollment.Where(s => listCourses.Contains(s.CourseId) && s.StudentId == id).Select(s => s.CourseId); IEnumerable <int> newCourses = listCourses.Where(s => !existCourses.Contains(s)); foreach (int courseId in newCourses) { _context.Enrollment.Add(new Enrollment { CourseId = courseId, StudentId = id }); } await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StudentExists(model.Student.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(model)); }
// GET: Students/Edit/5 public async Task <IActionResult> Edit(int?id) { if (id == null) { return(NotFound()); } var student = _context.Student.Where(s => s.Id == id).Include(s => s.Courses).First(); if (student == null) { return(NotFound()); } StudentCourseEdit viewModel = new StudentCourseEdit { Student = student, CourseList = new MultiSelectList(_context.Course.OrderBy(s => s.Title), "Id", "Title"), SelectedCourses = student.Courses.Select(sa => sa.CourseId) }; return(View(viewModel)); }