// GET: Instructor/Create public ActionResult Create() { var instructor = new Instructor {Courses = new List<Course>()}; PopulateAssigmentCourseData(instructor); return View(); }
private void UpdateInstructorCourses(Instructor instructorToUpdate, string[] selectedCoursesIds) { if (selectedCoursesIds == null || !selectedCoursesIds.Any()) { instructorToUpdate.Courses = new List<Course>(); return; } instructorToUpdate.Courses = instructorToUpdate.Courses ?? new List<Course>(); var parsedIds = selectedCoursesIds.Select(int.Parse); var instructorCoursesIds = instructorToUpdate.Courses.Select(c => c.CourseID).ToList(); var selectedCourses = _universityContext.Courses.Where(c => parsedIds.Contains(c.CourseID)); // remove courses foreach (var courseToDelete in instructorCoursesIds.Where(courseId => !selectedCourses.Any(c => c.CourseID == courseId))) { instructorToUpdate.Courses.Remove(instructorToUpdate.Courses.Single(c => c.CourseID == courseToDelete)); } // add courses foreach (var course in selectedCourses.Where(c => instructorCoursesIds.All(courseId => c.CourseID != courseId))) { instructorToUpdate.Courses.Add(course); } }
private void PopulateAssigmentCourseData(Instructor instructor) { var instructorCoursesIds = instructor.Courses.Select(c => c.CourseID); var assignedCourseData = from c in _universityContext.Courses select new AssignedCourseData() { CourseID = c.CourseID, Title = c.Title, Assigned = instructorCoursesIds.Contains(c.CourseID) }; ViewBag.Courses = assignedCourseData.ToList(); }