MVC + ViewModel Is the Real Deal

When creating ASP.Net applications for business and enterprise requirements, you are more likely doing something nowhere near basic. While simple MVC examples are available everywhere, the truth is, they are more often, if not always, NOT applicable as-is.

MVC is a good pattern. MVC + ViewModel makes it real. An average form in a business application may include parts and pieces that come from different sources. A UI can contain data for the actual module it represents, but it can also contain child data, lookup data, session, application and system specific data, and what have you. MVC may be good enough if everything is simple. Otherwise, and usually the case, adding a ViewModel actually makes more sense.

A ViewModel represents the actual data bound to the UI. This can include the main data source of the view, and also all other pieces of data that are important to the view's features. The ViewModel can also apply UI specific handling, such as data formatting, for example.

The ViewModel can be used to deliver front-end requirements, and MVC for everything else. You can think of the ViewModel as the view's own POCO. It can contain one or more domain POCOs plus any view-specific objects and pieces of data that are needed by the UI/UX. Standard UI/UX data-driven features can also be easily shared through the ViewModel (think IViewModel or ViewModelBase, perhaps?).

The MVC app's controller actions can be used to construct and/or deconstruct ViewModels, or perhaps via custom façade components/services that can be designed to provide ViewModel-level handling, mapping and other operations. It is important that the ViewModel does not contain data access instructions and business rules. However, it does not mean that ViewNodels should be anemic. Just watch out when data access and business rules are leaking in to your ViewModel codes. If so, then it is very likely that you're already doing something wrong.

Most of the time, MVC is not enough. Just like MVVM and MVP, MVC + ViewModel is a simple option when things get complicated. Just remember that you do not develop your apps to be an MVC, MVC + ViewModel, MVVM or MVP implementation. Don't be unnecessarily purist. Apply what you know where and when applicable. Be ready. Be flexible. Be smart.

Comments