0
我有點困惑...當我的視圖POST模型返回到我的操作時,如何將它保存回它來自的數據庫?
我有一個動作,需要一個ID,加載一個對象,並將其傳遞給綁定到該對象的類型的模型的視圖。
在編輯視圖提供的表單中的數據後,我將POST回送到另一個接受與模型完全相同的對象的操作。
但是在這一點上,我不能只調用Repository.Save,我想我現在有一個全新的對象,不再與發送到View的原始數據庫查詢相關聯。
那麼,如何更新先前查詢的對象並將更改保存到數據庫而不是從視圖中取回新對象?
我甚至嘗試從數據庫中獲取對象的新實例,並將查看返回的對象賦值給它,然後使用Repo.Save(),仍然沒有這樣的運氣。
我在這裏做錯了什麼?
控制器代碼:使用TryUpdateModel
方法
[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 });
}
你用什麼來訪問數據? – jfar 2010-02-09 20:42:54
linq到sql存儲庫 – BigOmega 2010-02-09 22:06:17