ProfK
ProfK

Reputation: 51063

How do I only update properties on the original (DB) object that have been changed in the view model?

For example, I have a DateCreated property on my Product and ProductDetailModel classes. Yet, on my Edit view, I have no DateCreated input, or any kind of storage. When I edit a product with a DateCreateded of 2013/03/17, the DateCreated that is posted back in the ProductDetailModel is always '0001/01/01'. Unless I add a hidden input for every unused field to my edit view, I will always lose this information.

Is there any method of telling which properties in ProductDetailModel were actually signed values, or are just default values because no form elements exist for them?

Do I have to write my own model binder that maintains, in the view model, a list of updated fields, so that I can only assign these values back to the original object before saving it?

Upvotes: 0

Views: 898

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

AutoMapper has a very nice feature that allows you to do that. Your view model should only contain the properties that are used by your view and then simply load the product to update from your data store and use AutoMapper to do the job of updating only the properties that are part of the view model:

[HttpPost]
public ActionResult Edit(EditProductViewModel viewModel)
{
    Product productToUpdate = repo.GetProduct(viewModel.Id);
    Mapper.Map<EditProductViewModel, Product>(viewModel, productToUpdate);
    // at this stage the product domain model will have only its properties updated
    // that were present in the view model (a.k.a in the view)
    repo.Update(productToUpdate);

    ...
}

Upvotes: 3

slippyr4
slippyr4

Reputation: 862

Load your Product from the repository, then overwrite fields that are represented in the view model, then save changes.

Note that a ViewModel should contain only data needed by the view; it likely overlaps a bit with your data model, but won't be the same. That's why you use a ViewModel rather than just passing your data model around.

Upvotes: 0

Related Questions