我有两个表 employee
和 employee course
一对多的关系 .
Needs :在编辑视图中更新表 employee
中的名称和 employeecourse
表中的 courseid
Problem :在编辑视图中单击“提交”按钮时,将删除所有数据并仅保存选中
刚刚下拉课程的课程
如果点击提交时(通过添加或删除课程)课程没有发生任何变化
按钮删除全部
code logic
我单击提交时尝试使用逻辑删除所有数据,然后保存所有数据
改变之后
意思是提交按钮做两个任务
员工编辑视图之前存在
-
删除课程
-
在此员工的编辑视图中完成所有更改后添加课程
see image below
code
model class EditEmployeeVm
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)
{
**//i need to save name employee changes in employee table and all courses changes in emloyeecourse table
//what is wrong here**
var emp = db.Employees
.Include(e => e.EmployeeCourses)
.FirstOrDefault(f => f.Id == model.Id);
foreach (var eec in emp.EmployeeCourses.ToList())
{
db.EmployeeCourses.Remove(eec);
}
foreach (var couseid in model.CourseIds)
{
db.EmployeeCourses.Add(new EmployeeCourse { CourseId = couseid, EmployeeId = emp.Id });
}
db.SaveChanges();
return View();
}
update
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();
}
I Try in code above under update section i can add data and save when click submit button but problem when click remove button to course by jquery it remove it but it not save changes of remove in database so that when open edit view again i see item i removed before how to solve that when click submit button to save item removed in database