开发者

Edit method didn't works as explained in a popular book

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 开发者_C百科retrieve the product from the repository?

Thanks.


You don't need the extra TryUpdateModel method call because MVC has already updated your model when you receive it as a parameter in your Edit method.

[HttpPost]
public ActionResult Edit(Product product) {
    if (ModelState.IsValid) {
        repository.SaveProduct(product);
        return RedirectToAction("Index");
    } else {
        // there is something wrong with the data values
        return View(product);
    }
}

Your SaveProduct method does not handle the editing of a detached entity correctly.

public void SaveProduct(Product product)
{
    if (product.ProductID == 0)
    {
        context.Products.Add(product);
    }
    else
    {
       var entry = context.Entry(product);
       entry.State = EntityState.Modified;
    }         
    context.SaveChanges();
}


Creating an EF Data Model explains all of this


The difference is in what the context knows about the connection between the entity in memory and the data on the disk.

When you get an entity into one of your methods the context does not know anything about it. So it cannot save it. If you pull a row form the database and update it, the context knows that it has been updated and can save it.

The other thing that you could do would be to attach the incoming entity to a context.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜