ahmed salah

ahmed salah

  • NA
  • 530
  • 148.8k

using foreach to save data not save courses correctly

Sep 3 2016 1:48 PM

Needs

save name in employee table and save all courses

in employee courses table when click submit button in edit [HTTPPOST]

Problem summary

submit button save changes only and delete data exist before

Problem details

when click submit button in edit post .courses will save

what i added or selected courses before click submit it will save

but courses that employee have before will delete

Example

1- i add employee name MEDO have course c++

2-in edit view it show c++

3-if i add python in edit view then click submit it must have two courses

c++ and python

4- it show to me python only when open edit for this employee again

it save courses selected but courses exist before deleted

Image for problem

image found below show all details


SAVE all courses in employeecourse table

Code

  1. public class EditEmployeeVm  
  2. {  
  3. public int Id { setget; }  
  4. public string Name { getset; }  
  5. public List<SelectListItem> Courses { getset; }  
  6. public int[] CourseIds { setget; }  
  7. public List<CourseVm> ExistingCourses { setget; }  
  8. }  
  9.   
  10. public class CourseVm  
  11. {  
  12. public int Id { setget; }  
  13. public string Name { setget; }  
  14. }  
  15. in edit function get i pass data to edit view  
  16.   
  17. public ActionResult Edit(int id)  
  18. {  
  19. var vm = new EditEmployeeVm { Id = id };  
  20. var emp = db.Employees.FirstOrDefault(f => f.Id == id);  
  21. vm.Name = emp.Name;  
  22. vm.ExistingCourses = db.EmployeeCourses  
  23. .Where(g => g.EmployeeId == id)  
  24. .Select(f => new CourseVm  
  25. {  
  26. Id = f.Id,  
  27. Name = f.Course.CourseName  
  28. }).ToList();  
  29.   
  30. vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();  
  31. vm.Courses = db.Courses.Select(f => new SelectListItem  
  32. {  
  33. Value = f.Id.ToString(),  
  34. Text = f.CourseName  
  35. }).ToList();  
  36.   
  37. return View(vm);  
  38. }  
  39.   
  40.   
  41.   
  42. [HttpPost]  
  43. public ActionResult Edit(EditEmployeeVm model)  
  44. {  
  45. var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);  
  46. foreach (EmployeeCourse eec in emp.EmployeeCourses.ToList())  
  47. {  
  48. var ec = db.EmployeeCourses.Find(eec.Id);  
  49. db.EmployeeCourses.Remove(ec);  
  50. db.SaveChanges();  
  51. }  
  52.   
  53. foreach (var couseid in model.CourseIds)  
  54. {  
  55. db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });  
  56. db.SaveChanges();  
  57. }  
  58.   
  59. return View();  
  60. }  

Answers (1)