cannot save changes of courses if remove in edit httppost [Resolved]

Posted by Ahmedsa under ASP.NET MVC on 9/10/2016 | Points: 10 | Views : 491 | Status : [Member] | Replies : 1
Problem
when remove course then click submit not save changes although
it removed from client side by jquery
Details
in edit view for every employee i need to do changes by remove or add new courses for employee
if i add new courses then click submit button it save what i do
but if i remove course from courses then click submit it will not save courses i removed
so that i need to check what is wrong in my code
my code working without any problem but only have problem
i cannot save courses removed in database in employeecourse table when click submit
employeecourse table have Id,EmployeeId,CourseId
jquery remove client side attached with my question
code
my code as following
 [HttpPost]  
public ActionResult Edit(EditEmployeeVm model)
{
var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);
foreach (var couseid in model.CourseIds)
{
db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
db.SaveChanges();
}

return View();
my(custom model) view model using for that
public class EditEmployeeVm
{
public int Id { set; get; }
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; }
}
}

to show what i need clearly see image below




Responses

Posted by: Rajnilari2015 on: 9/12/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
The code

  db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });  
db.SaveChanges();


will add/insert a Course and not remove. For removing, you should use Remove method like

var emp = db.Employees.FirstOrDefault(f => f.Id == model.Id);  
db.EmployeeCourses.Remove(emp);
db.SaveChanges();


For your reference, please read CRUD using Code First Approach of Entity Framework (EF) ( http://www.dotnetfunda.com/articles/show/3314/crud-using-code-first-approach-of-entity-framework-ef ) which will help you to clear the concept.

Hope that helps. Let us know in case of any concern.





--
Thanks & Regards,
RNA Team

Ahmedsa, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response