0

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?

ProfK
  • 49,207
  • 121
  • 399
  • 775

2 Answers2

3

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);

    ...
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Aaah, I've actually been doing that, but while writing an article, I imagined a situation otherwise. This is on my View Model, `public virtual void ApplyToEntity(TEntity entity) { Mapper.Map(this, entity, GetType(), typeof(TEntity)); `}` – ProfK Mar 17 '13 at 18:57
  • i am getting shipping address details from user using a form generated with `View Model`, i want to check if postedFormValues != existing shipping address details in database, if true then update modified shipping details in database, can we use `auto mapper` ? if yes, can you show an example or should i ask separate question ? – Shaiju T Nov 28 '15 at 14:13
0

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.

slippyr4
  • 862
  • 7
  • 18
  • Yes, a ViewModel should as closely bound to a view as well as it takes to use the ViewModel to determine ever property value correctly which is different to the original value. I suspect the addition of a properties changed record, and we shall use AutoMapper to sort the rest out. – ProfK Mar 17 '13 at 19:43