Mitkins Mitkins - 1 year ago 84
C# Question

Should I implement business logic on a Model or a ViewModel

When I'm processing business logic in an MVVM app. Should I do this on the Model or the ViewModel?

For example, if I want to re-calculate costs after an Asset has been re-valued, should I operate on the Model?

Is there an advantage in doing this on the ViewModel instead?

What happens if I have a list of ViewModels, but I want to translate that into a list of Models so I can do some processing? I could expose the Model as a property of the ViewModel (and use that to build the list of Models). But that means that the View will be able to access properties of the original Model

Answer Source

The Model's purpose is to represent (or model) your business domain. Therefore, business logic by definition goes in the Model, not the ViewModel.

The job of the ViewModel is to expose properties and fields of the Model, and prepare them for consumption by the View.

For instance, picture a banking application. The Model may represent an account. Perhaps the Model has an account balance. The job of the Model may be to track the balance and make sure certain invariants are maintained (such as not allowing a withdrawal that is larger than the balance). The job of the ViewModel may be to turn the balance into a string that is used as a binding in the View.

You want to keep as much logic out of the ViewModel as possible to keep your code reusable and loosely coupled.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download