public async Task <IActionResult> EnrollMultiple(int?id) { var course = await _context.Course.Where(m => m.Id == id).Include(m => m.Students).FirstOrDefaultAsync(); var vm = new EnrollMultipleViewModel { StudentsList = new MultiSelectList(_context.Student.OrderBy(s => s.FirstName), "Id", "FullName"), SelectedStudents = course.Students.Select(sa => sa.StudentId) }; ViewData["CourseName"] = _context.Course.Where(c => c.Id == id).Select(c => c.Title).FirstOrDefault(); ViewData["chosenId"] = id; return(View(vm)); }
public async Task <IActionResult> EnrollMultiple(int id, EnrollMultipleViewModel vm) { if (id != vm.NewEnrollment.CourseId) { return(NotFound()); } IEnumerable <double> listStudents = vm.SelectedStudents; IEnumerable <double> existStudents = _context.Enrollment.Where(s => listStudents.Contains(s.StudentId) && s.CourseId == id).Select(s => s.StudentId); IEnumerable <double> newStudents = listStudents.Where(s => !existStudents.Contains(s)); foreach (double sid in newStudents) { _context.Enrollment.Add(new Enrollment { StudentId = sid, CourseId = id, Year = vm.NewEnrollment.Year, Semester = vm.NewEnrollment.Semester }); } await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }