I bought a book about MVC 3. In this book, there is an example for the implementation of an edit method. Below is the code:
[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);
}
}
This code works very well for the creation of a newly product but didn’t work for the edition of an exisiting product.
I updated the code for successfully editing a product (see code below):
[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);
}
}
EDIT
Here is the Saveproduct method:
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
{
context.Products.Add(product);
}
context.SaveChanges();
}
As you can see, the modification I do in the code is about retrieving the product based on his ID, then save the product.
My question: why the second method works and not the first one? In the second method, why do we have to retrieve the product from the repository?
Thanks.
You don’t need the extra
TryUpdateModelmethod call because MVC has already updated your model when you receive it as a parameter in yourEditmethod.Your
SaveProductmethod does not handle the editing of a detached entity correctly.