我有点困惑...
我有一个动作,它需要一个 ID,加载一个对象,然后将它传递给绑定到该对象类型的模型的视图。
在视图提供的表单中编辑数据后,我 POST 回另一个操作,该操作接受与模型完全相同类型的对象。
但是此时我不能只调用 Repository.Save,我想我现在有一个全新的对象,不再与发送到视图的原始数据库查询中的对象相关联。
那么如何更新先前查询的对象并将更改保存到数据库而不是从视图中获取新对象呢?
我什至尝试从数据库中获取对象的新实例并将返回的视图对象分配给它,然后是 Repo.Save(),仍然没有这样的运气。
我在这里做错了什么?
控制器代码:
[Authorize]
public ActionResult EditCompany(int id)
{
//If user is not in Sys Admins table, don't let them proceed
if (!userRepository.IsUserSystemAdmin(user.UserID))
{
return View("NotAuthorized");
}
Company editThisCompany = companyRepository.getCompanyByID(id);
if (editThisCompany == null)
{
RedirectToAction("Companies", new { id = 1 });
}
if (TempData["Notify"] != null)
{
ViewData["Notify"] = TempData["Notify"];
}
return View(editThisCompany);
}
//
// POST: /System/EditCompany
[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditCompany(Company company)
{
string errorResponse = "";
if (!isCompanyValid(company, ref errorResponse))
{
TempData["Notify"] = errorResponse;
return RedirectToAction("EditCompany", new { id = company.CompanyID });
}
else
{
Company updateCompany = companyRepository.getCompanyByID(company.CompanyID);
updateCompany = company;
companyRepository.Save();
return RedirectToAction("EditCompany", new { id = company.CompanyID });
}
return RedirectToAction("Companies", new { id = 1 });
}