I am working on a client/server (WPF/WCF) application using the MVVM pattern.
Properties on the ViewModel are bound to properties on the Model such that when the Model is changed, the change is propagated immediately to the View.
When the user clicks refresh, any new/changed data on the server is merged into Model, so the refresh mechanism is working well.
How do I handle the user editing and saving properties? Here is what I want to happen:
- User clicks “Edit”
- User modifies values in TextBoxes
- User clicks “Save”
- Changes are sent to server
- If successful, server returns updated item, which is merged into
Model, and the UI is updated.- If not successful, server returns error and Model is not updated.
It seems that by using MVVM, the Model is updated at step 3 (making steps 5 & 6 redundant), and if an error occurs on the server, data at the client becomes inconsistent with the server.
Is there a best practice way to deal with this situation?
The solution I have come up with is to create a second set of objects – ModelUpdates.
When the user clicks Edit, a ModelUpdate object (which has the same properties as the Model object) is instantiated and the DataContext is switched to that object.
When the user clicks Save, details of the ModelUpdate object are sent to the service. The service responds with details about the updated object, which are then merged into the Model repository.
This means that the Model is only ever updated with data that has been successfully saved. If the object was saved incorrectly, the database version will be sent back to the client. If an error occurred in saving, the database version will be sent back to the client. If the server is unavailable, the client will keep the pre-edit version.