public async Task <IActionResult> OnPostDeleteCourseAsync(int?id)
        {
            _logger.LogWarning($"OnPost: StudentId {id}, DROP course {CourseIdToDelete}");
            if (id == null)
            {
                return(NotFound());
            }

            Student = await _context.Student.Include(s => s.StudentCourses).ThenInclude(sc => sc.Course).FirstOrDefaultAsync(m => m.StudentID == id);

            //AllCourses = await _context.Course.ToListAsync();
            //CoursesDropDown = new SelectList(AllCourses, "CourseID", "Description");

            if (Student == null)
            {
                return(NotFound());
            }

            StudentCourse courseToDrop = _context.StudentCourse.Find(CourseIdToDelete, id.Value);

            if (courseToDrop != null)
            {
                _context.Remove(courseToDrop);
                _context.SaveChanges();
            }
            else
            {
                _logger.LogWarning("Student NOT enrolled in course");
            }

            return(RedirectToPage(new { id = id }));
        }
Beispiel #2
0
        private void UpdateStudentCourses(int[] selectedCourses, Student studentToUpdate)
        {
            if (selectedCourses == null)
            {
                studentToUpdate.StudentCourses = new List <StudentCourse>();
                return;
            }

            List <int> currentCourses      = studentToUpdate.StudentCourses.Select(c => c.CourseID).ToList();
            List <int> selectedCoursesList = selectedCourses.ToList();

            foreach (var course in _context.Course)
            {
                if (selectedCoursesList.Contains(course.CourseID))
                {
                    if (!currentCourses.Contains(course.CourseID))
                    {
                        // Add course here
                        studentToUpdate.StudentCourses.Add(
                            new StudentCourse {
                            StudentID = studentToUpdate.StudentID, CourseID = course.CourseID
                        }
                            );
                        _logger.LogWarning($"Student {studentToUpdate.FirstName} {studentToUpdate.LastName} ({studentToUpdate.StudentID}) - ADD {course.CourseID} {course.Description}");
                    }
                }
                else
                {
                    if (currentCourses.Contains(course.CourseID))
                    {
                        // Remove course here
                        StudentCourse courseToRemove = studentToUpdate.StudentCourses.SingleOrDefault(s => s.CourseID == course.CourseID);
                        _context.Remove(courseToRemove);
                        _logger.LogWarning($"Student {studentToUpdate.FirstName} {studentToUpdate.LastName} ({studentToUpdate.StudentID}) - DROP {course.CourseID} {course.Description}");
                    }
                }
            }
        }