public JobDutyEditEmployees ( |
||
newItem | ||
return |
public JobDutyWithEmployees JobDutyEditEmployees(JobDutyEditEmployees newItem)
{
// Attempt to fetch the object
// When editing an object with a to-many collection,
// and you wish to edit the collection,
// MUST fetch its associated collection
var o = ds.JobDuties.Include("Employees")
.SingleOrDefault(e => e.Id == newItem.Id);
if (o == null)
{
// Problem - object was not found, so return
return null;
}
else
{
// Update the object with the incoming values
// First, clear out the existing collection
o.Employees.Clear();
// Then, go through the incoming items
// For each one, add to the fetched object's collection
foreach (var item in newItem.EmployeeIds)
{
var a = ds.Employees.Find(item);
o.Employees.Add(a);
}
// Save changes
ds.SaveChanges();
return Mapper.Map<JobDutyWithEmployees>(o);
}
}
}
public ActionResult JobDutyAndEmployees(int?id, JobDutyEditEmployees newItem) { // Validate the input if (!ModelState.IsValid) { // Our "version 1" approach is to display the "edit form" again return(RedirectToAction("JobDutyAndEmployees", new { id = newItem.Id })); } if (id.GetValueOrDefault() != newItem.Id) { // This appears to be data tampering, so redirect the user away return(RedirectToAction("ByJobDuty")); } // Attempt to do the update var editedItem = m.JobDutyEditEmployees(newItem); if (editedItem == null) { // There was a problem updating the object // Our "version 1" approach is to display the "edit form" again return(RedirectToAction("ByJobDuty", new { id = newItem.Id })); } else { // Show the details view, which will have the updated data return(RedirectToAction("ByJobDutyWithEmployees", new { id = newItem.Id })); } }