public async Task <IActionResult> Create([Bind("Id,ForYear,Approved,FkUsers,FkBooks,SchoolClassesRequests")] Requests requests) { if (ModelState.IsValid) { // Set property of object (Years, Approved) requests.FkYears = StartController._currentYear.Id; requests.Approved = 1; // if there no user in request set it automaticlly if (requests.FkUsers != 0) { requests.FkUsers = requests.FkUsers; } else { requests.FkUsers = StartController._currentUser.Id; } _context.Add(requests); await _context.SaveChangesAsync(); // get the id of selected classes var schoolClassesIds = Request.Form["SchoolClassesRequests"]; // For each id create a schoolclassesrequestd foreach (string schoolClassesId in schoolClassesIds) { // create an object with parameters SchoolClassesRequests schoolClassesRequest = new SchoolClassesRequests { FkRequests = requests.Id, FkSchoolClasses = Int32.Parse(schoolClassesId) }; _context.Add(schoolClassesRequest); await _context.SaveChangesAsync(); } return(RedirectToAction(nameof(Index))); } return(View(requests)); }
public async Task <IActionResult> Edit(int id, [Bind("Id")] Requests requests) { if (id != requests.Id) { return(NotFound()); } if (ModelState.IsValid) { try { // get the id of selected classes var schoolClassesIds = Request.Form["SchoolClassesRequests"]; // get old school classes var oldSchoolClasses = _context.SchoolClassesRequests.Where(r => r.FkRequests == requests.Id).ToList().Select(s => s.FkSchoolClasses.ToString()).ToArray(); // get delete school classes foreach (string el in oldSchoolClasses) { if (!schoolClassesIds.Contains(el)) { // Get element to delete it var delEl = _context.SchoolClassesRequests.Where(r => r.FkRequests == requests.Id && r.FkSchoolClasses == Int32.Parse(el)).First(); // Delete in database _context.Remove(delEl); await _context.SaveChangesAsync(); } } // For each id create a schoolclassesrequestd foreach (string schoolClassesId in schoolClassesIds) { var alreadyExistItem = _context.SchoolClassesRequests.Where(r => r.FkRequests == requests.Id && r.FkSchoolClasses == Int32.Parse(schoolClassesId)).FirstOrDefault(); if (alreadyExistItem == null) { // create an object with parameters SchoolClassesRequests schoolClassesRequest = new SchoolClassesRequests { FkRequests = requests.Id, FkSchoolClasses = Int32.Parse(schoolClassesId) }; _context.Add(schoolClassesRequest); await _context.SaveChangesAsync(); } } } catch (DbUpdateConcurrencyException) { if (!RequestsExists(requests.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(requests)); }