1 Replies - 443 Views - Last Post: 04 September 2016 - 05:17 AM

#1 ahmedba  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 24-January 14

using foreach to save data not save courses correctly

Posted 03 September 2016 - 04:17 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

Posted Image

SAVE all courses in employeecourse table

Code

public class EditEmployeeVm
{
public int Id { set; get; }
public string Name { get; set; }
public List<SelectListItem> Courses { get; set; }
public int[] CourseIds { set; get; }
public List<CourseVm> ExistingCourses { set; get; }
}

public class CourseVm
{
public int Id { set; get; }
public string Name { set; get; }
}
in edit function get i pass data to edit view

public ActionResult Edit(int id)
{
var vm = new EditEmployeeVm { Id = id };
var emp = db.Employees.FirstOrDefault(f => f.Id == id);
vm.Name = emp.Name;
vm.ExistingCourses = db.EmployeeCourses
.Where(g => g.EmployeeId == id)
.Select(f => new CourseVm
{
Id = f.Id,
Name = f.Course.CourseName
}).ToList();

vm.CourseIds = vm.ExistingCourses.Select(g => g.Id).ToArray();
vm.Courses = db.Courses.Select(f => new SelectListItem
{
Value = f.Id.ToString(),
Text = f.CourseName
}).ToList();

return View(vm);
}



[HttpPost]
public ActionResult Edit(EditEmployeeVm model)
{
var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);
foreach (EmployeeCourse eec in emp.EmployeeCourses.ToList())
{
var ec = db.EmployeeCourses.Find(eec.Id);
db.EmployeeCourses.Remove(ec);
db.SaveChanges();
}

foreach (var couseid in model.CourseIds)
{
db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
db.SaveChanges();
}

return View();
}



Is This A Good Question/Topic? 0
  • +

Replies To: using foreach to save data not save courses correctly

#2 ahmedba  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 141
  • Joined: 24-January 14

Re: using foreach to save data not save courses correctly

Posted 04 September 2016 - 05:17 AM

can any one help me in that
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1