I have 3 tables: Companies, Subcontracts, and CompanyToSubcontract
The CompanyToSubcontract table is the guid of the Company and guid of the Subcontract. I have a MultiSelectList on the Subcontract Edit and Create views where the user can select multiple companies. I finally got it working where it displays the correct companies as selected in the Subcontract Edit view. I'm not having an issue with saving the data.
In the create view, the subcontract doesn't have a guid until it's written to the Sql database, so how can I get the guid to save to the CompanyToSubcontract table?
Also, in the edit view, I'm doing something wrong. It doesn't save.the company selections. I also need to delete records for companies which are unselected. What is the best way to go about doing that?
I followed the NerdDinner tutorial to get my basic structure and now I'm trying to update to fulfill my needs.
Anyone who can point me in the right direction?
In SubcontractRepository:
public void Save()
{
db.SubmitChanges();
}
In Controller:
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult Edit(string id, FormCollection formValues)
{
// Retrieve existing subcontract
subcontract subcontract = subcontractRepository.GetSubcontract(id);
if (subcontract == null)
return View("NotFound");
else
{
try
{
UpdateModel(subcontract);
IEnumerable<Guid> selectedCompanies = Request.Form["Companies"].Split(new Char[] { ',' }).Select(idStr => new Guid(idStr));
foreach (var item in selectedCompanies)
{
CompanyToSubcontract cs = new CompanyToSubcontract();
cs.subcontract_id = subcontract.subcontract_id;
cs.company_id = item;
subcontractRepository.Save();
}
subcontract.lastupdate_date = DateTime.Now;
subcontract.lastupdatedby_user = User.Identity.Name;
//Persist changes back to database
subcontractRepository.Save();
//Perform HTTP redirect to details page for the saved subcontract
return RedirectToAction("Details", new { id = subcontract.subcontract_no });
}
catch
{
ModelState.AddRuleViolations(subcontract.GetRuleViolations());
return View(new SubcontractFormViewModel(subcontract));
}
}
}