2010-02-09 33 views
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 }); 
} 
+0

你用什麼來訪問數據? – jfar 2010-02-09 20:42:54

+0

linq到sql存儲庫 – BigOmega 2010-02-09 22:06:17

回答

0

嘗試。通過這種方式,您可以在數據綁定之前從存儲庫中獲取公司。

[Authorize] 
[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult EditCompany(int id, FormCollection form) 
{ 
    //Default to a new company 
    var company = new Company(); 

    //If we have an id, we must be editing a company so get it from the repo 
    if (id > 0) 
     company = companyRepository.getCompanyByID(id); 

    //Update the company with the values from post 
    if (TryUpdateModel(company, form.ToValueProvider())) 
    { 
     string errorResponse = ""; 

     if (!isCompanyValid(company, ref errorResponse)) 
     { 
      TempData["Notify"] = errorResponse; 
      return RedirectToAction("EditCompany", new { id = company.CompanyID }); 
     } 
     else 
     { 
      companyRepository.Save(); 
      return RedirectToAction("EditCompany", new { id = company.CompanyID }); 
     } 
    } 

    return RedirectToAction("Companies", new { id = 1 }); 
} 

HTHS,
查爾斯

聚苯乙烯。一般來說,將數據綁定到您的域模型是個不錯的主意......使用演示模型,然後您可以解決整個問題。

相關問題