MVC vs MVVM – Difference Between Controller and ViewModel

asp.netdesign-patternssilverlight

I can't see the difference between MVC and MVVM clearly. I feel the Command in a ViewModel is just like the Action method in a Controller. And both the Controller and ViewModel will notify the View to refresh itself after modifying the state of the Model through Data Binding. What is the main difference between the two patterns?

Best Answer

The controller and the ViewModel differ in various ways.

In MVC the Controller knows the view, it can change the View. It also knows the Model and can call it. In MVVM a ViewModel is an abstract representation of the View and does not know the concrete UI, it wraps the Model in a way so that it can be displayed as desired.

In classical MVC, a controller is just a strategy of the View to interact with the Model. In fact, sometimes a Controller isn't even necessary. In MVVM you don't need it, as you can have different ViewModels for the same View if you need different behaviours. In MVC you could have for example a ReadOnlyController or an AdminController to communicate with the Model. In MVVM you could just have two ViewModels and you choose the one you need for the View.

But they do have some similarities. In both patterns, the View is an observer. In classical MVC, the view is an observer of the model, in MVVM it's an observer of the ViewModel.

Both patterns are meant to provide a separation of concerns. MVVM primarily aims to provide an abstraction of the View, completely independent of the UI technology in use. MVC does not go that far. It's primary focus is on separation of concerns, so that you don't put business logic (the Model) into the view.

You might also find this answer of mine to a similar question helpful.

At last, I should say that both patterns belong to the same family. MVP, of which MVVM is a descendant is a sibling of MVC. If you want to know more follow this link to Martin Fowler's website, he explains everyting in detail.