我買了一本關於MVC 3的書。在本書中,有一個編輯方法實現的例子。以下是代碼:編輯方法沒有按照流行書中的解釋工作
[HttpPost]
public ActionResult Edit(Product product) {
if (ModelState.IsValid) {
TryUpdateModel(product);
repository.SaveProduct(product);
return RedirectToAction("Index");
} else {
// there is something wrong with the data values
return View(product);
}
}
此代碼適用於創建新產品,但不適用於現有產品的版本。
我更新的代碼成功地修改產品(見下面的代碼):
[HttpPost]
public ActionResult Edit(Product prod)
{
if (ModelState.IsValid)
{
Product product = repository.Products.FirstOrDefault(p => p.ProductID == prod.ProductID);
TryUpdateModel(product);
repository.SaveProduct(product);
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(prod);
}
}
編輯
這裏是Saveproduct方法:
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
context.SaveChanges();
}
正如你所看到的,我在代碼中做的修改是關於基於他的ID檢索產品,然後保存產品。
我的問題:爲什麼第二種方法有效,而不是第一種?在第二種方法中,爲什麼我們必須從存儲庫中檢索產品?
謝謝。
你可以發表你的資料庫的'SaveProduct'方法? – Eranga
..以及TryUpdateModel方法?可能還有產品類和編輯視圖的內容... – marapet
@marapet:TryUpdateModel是一個MVC功能,不是我的產品類是非常經典的:int ProductID,string名稱,字符串說明... – Bronzato