1362

Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?

Bjorn Reppen
  • 20,343
  • 8
  • 51
  • 84
  • 67
    Note that while MVVM was coined by Microsoft, plenty of non-Microsoft developers and projects have begun to adopt this pattern. This comment was brought to you by the spite-the-MS-haters department. – BoltClock Oct 08 '13 at 05:10
  • 1
    Having worked with MVVM for a long time, my first brush with MVC was frustrating, until I learned I could pass ViewModels back and forth to the browser using binding techniques found in MVVM. But as Joel said above the only way to get state back from the browser is by posting the changes in a form (which uses name/value) pairs. If you don't understand this point well. You will have a hard time in MVC. Just look at the controller as a dependency injector for the view and you're all set. – JWP Oct 15 '14 at 13:27
  • 4
    Such an upvoted question on high-level [design patterns]. I would kindly like to suggest the use of diagrams on the answers. – Ricardo Feb 10 '15 at 18:33
  • Also a re-wording of the question to reflect the fact that the question is asked in the context of Microsoft technologies...although the accepted answer sort of is not. – Dave Kanter Dec 23 '15 at 19:17
  • 4
    Here's an archived version of Joel's article: https://web.archive.org/web/20150219153055/http://joel.inpointform.net/software-development/mvvm-vs-mvp-vs-mvc-the-differences-explained/ – Tereza Tomcova Jul 07 '17 at 13:26
  • 3
    Unlike the MVC method, the ViewModel isn’t a controller. It instead acts as a binder that binds data between the view and model. Whereas the MVC format is specifically designed to create a separation of concerns between the model and view, the MVVM format with data-binding is designed specifically to allow the view and model to communicate directly with each other. https://hackernoon.com/mvc-vs-mvvm-how-a-website-communicates-with-its-data-models-18553877bf7d – blueray Dec 06 '17 at 12:20
  • [Code examples of Design Patterns in various languages: C#, C++, Go, Java, JavaScript, Python, and Swift.](https://github.com/MilovanTomasevic/Design-Patterns) – Milovan Tomašević Apr 18 '21 at 19:04

25 Answers25

705

MVC/MVVM is not an either/or choice.

The two patterns crop up, in different ways, in both ASP.Net and Silverlight/WPF development.

For ASP.Net, MVVM is used to two-way bind data within views. This is usually a client-side implementation (e.g. using Knockout.js). MVC on the other hand is a way of separating concerns on the server-side.

For Silverlight and WPF, the MVVM pattern is more encompassing and can appear to act as a replacement for MVC (or other patterns of organising software into separate responsibilities). One assumption, that frequently came out of this pattern, was that the ViewModel simply replaced the controller in MVC (as if you could just substitute VM for C in the acronym and all would be forgiven)...

The ViewModel does not necessarily replace the need for separate Controllers.

The problem is: that to be independently testable*, and especially reusable when needed, a view-model has no idea what view is displaying it, but more importantly no idea where its data is coming from.

*Note: in practice Controllers remove most of the logic, from the ViewModel, that requires unit testing. The VM then becomes a dumb container that requires little, if any, testing. This is a good thing as the VM is just a bridge, between the designer and the coder, so should be kept simple.

Even in MVVM, controllers will typically contain all processing logic and decide what data to display in which views using which view models.

From what we have seen so far the main benefit of the ViewModel pattern to remove code from XAML code-behind to make XAML editing a more independent task. We still create controllers, as and when needed, to control (no pun intended) the overall logic of our applications.

The basic MVCVM guidelines we follow are:

  • Views display a certain shape of data. They have no idea where the data comes from.
  • ViewModels hold a certain shape of data and commands, they do not know where the data, or code, comes from or how it is displayed.
  • Models hold the actual data (various context, store or other methods)
  • Controllers listen for, and publish, events. Controllers provide the logic that controls what data is seen and where. Controllers provide the command code to the ViewModel so that the ViewModel is actually reusable.

We also noted that the Sculpture code-gen framework implements MVVM and a pattern similar to Prism AND it also makes extensive use of controllers to separate all use-case logic.

Don't assume controllers are made obsolete by View-models.

I have started a blog on this topic which I will add to as and when I can (archive only as hosting was lost). There are issues with combining MVCVM with the common navigation systems, as most navigation systems just use Views and VMs, but I will go into that in later articles.

An additional benefit of using an MVCVM model is that only the controller objects need to exist in memory for the life of the application and the controllers contain mainly code and little state data (i.e. tiny memory overhead). This makes for much less memory-intensive apps than solutions where view-models have to be retained and it is ideal for certain types of mobile development (e.g. Windows Mobile using Silverlight/Prism/MEF). This does of course depend on the type of application as you may still need to retain the occasional cached VMs for responsiveness.

Note: This post has been edited numerous times, and did not specifically target the narrow question asked, so I have updated the first part to now cover that too. Much of the discussion, in comments below, relates only to ASP.Net and not the broader picture. This post was intended to cover the broader use of MVVM in Silverlight, WPF and ASP.Net and try to discourage people from replacing controllers with ViewModels.

Gone Coding
  • 88,305
  • 23
  • 172
  • 188
  • 8
    @Tomasz Zielinski: True, but "where they are used" was not the question (or the point of my answer). My point is that controllers are still useful in MVVM. – Gone Coding Jul 14 '11 at 07:43
  • 60
    I agree. My comment was caused by sudden enlightement and not because I disagreed with you. – Tomasz Zieliński Jul 14 '11 at 14:57
  • We also used controllers to control the "flow" of views in a wizard-like UI. – riezebosch Aug 15 '12 at 14:28
  • The cause of confusion comes from what ASP.NET MVC calls "ViewModel", because, when implementing Rails interpretation of MVC, there is no view, only templates while people call "views". In ASP.NET MVC the ViewModel actually a full implemented View from Model2 MVC pattern (active view which requests data from model layer and manipulates multiple templates based on that data). – tereško Sep 09 '12 at 09:37
  • What you are saying makes perfect sense (the VM shouldn't contain logic), however I'm struggling to see how it would work in practice - for example what unit-testable piece of logic is executed when the user clicks on a button? How about when the user modifies a text box which is two-way databound to a property on the ViewModel? – Justin Jun 12 '13 at 08:16
  • 3
    @Justin: I see my wording of that sentence is a little ambiguous. I actually mean unit-testing for all components is more easily supported, not specifically just improving testing of ViewModels (which as you point out don't actually do that much in MVCVM... which is what you want). The real benefit of controllers is that you are actually removing most of the requirements for testing from the ViewModel (where people keeps shoving controller logic) and putting it where it can be tested (mainly Controllers and Models). The reuse comment is specific to the VMs in that sentence. I have edited it. – Gone Coding Jun 12 '13 at 09:37
  • I don't understand what's the difference between MVVM and MVC with Controller Service pattern ...... – jpic Jul 02 '13 at 10:59
  • @jpic: MVVM does not normally *encourage* separation of controllers (which I am encouraging). MVC also uses ViewModels, as well as models, so should it not also be called MVCVM and both follow the same pattern... hmmm? :) – Gone Coding Jul 03 '13 at 09:40
  • Please elaborate on the role of ViewModel in two-way data binding. The Controller gets and puts ViewModels from and to the View. What type of Entity (Controller?) mediates getting and putting between the ViewModel and (one or more) Models? – subsci Sep 16 '13 at 16:55
  • @subsci: Two-way binding, in MVVM, is purely a way of mirroring values in both the View and View-Model allowing the changes to reflect elsewhere in the View(s). Binding direct to actual data sources in a GUI app can be quite a fragile connection (e.g. not resistant to comms failures), so better to persist data under the specific control of a Controller, e.g. in response to a `Save` option/command. Controllers can instantiate data connection objects as and when needed (like EF does). I am assuming you will persist your data with WCF RIA services? – Gone Coding Jan 08 '14 at 09:38
  • So basically you are not disagreeing with TStamper's answer, which is also what appears to be the description of Microsoft itself at http://msdn.microsoft.com/en-us/magazine/dd419663.aspx, instead you propose that MVVM is wrong and instead one should use MVCVM, also since many claim that a controller is not one to one (see http://stackoverflow.com/questions/1593976/benefits-of-mvvm-over-mvc/1594130#1594130) you would probably have to call it MVPVM – yoel halb Jul 27 '14 at 06:05
  • I've found them both lacking. MVC frameworks like Rails handle even simply joins poorly (try building a selection on a relation using a scope from that associated record) while Microsoft's MVVM in trying to fix some problems in MVC ends up being painfully coupled and klunky. – Mike Bethany Oct 15 '14 at 10:13
  • I disagree with the concept that the controllers are anything more than 1) A route handler and 2) The minder of he ViewModel. From a controller perspective the VM only needs two methods 1)The null CTOR which MVC must have anyway, and 2) A POST method. The controller is just a traffic cop, it handles events either newing up a viewmodel or calling it's Post method. The view model then can either contain models, create models, has collections and keeps the state. It can also contain business logic. Putting a bunch of code into the controller doesn't make sense to me. – JWP Oct 15 '14 at 13:34
  • @user1522548: You are certainly entitled to disagree. My opinion was/is based on a wide variety of requirements for logic separation and simplification of ViewModels. MVVM encompasess Silverlight, WPF and web apps, not only the simple case of ASP/MVC you reference. Thanks. – Gone Coding Oct 15 '14 at 13:37
  • I am a strongly typed bigot, for me the Viewmodel approach to MVC is the only way to fly. This means that much if not all of the states and datacontext is moved to the VM layer. In my projects, the controller is just an injector of viewmodels (either new ones or altered content due to a post). The VM in my projects uses the EF layer extensively because I've found EF can do anything and do it well with strongly typed models. But what I've noticed in the MVC world is that there's still a huge contingency for non-strong typed solutions. This is a hold over from query string parsing. – JWP Oct 15 '14 at 14:03
  • @user1522548: *Coding by convention* (i.e. not strongly typed) is one of the more powerful features of MVC, but if you don't use/like it then you will obviously find other solutions. I suggest you compile your ideas into an alternate answer to this question and get some feedback :) – Gone Coding Oct 15 '14 at 14:06
  • Ya I use that too, but for tables with thousands of fields why bother? EF can give me strong types of entire database in 2 minutes. I work with an old school asp.net guy who still does all that stuff you know, Name/Value pairs all typed in for everything he does. He likes what EF does but doesn't yet grasp the benefits. Couple EF with LINQ and I'll never touch a database again. But just look at some of the newer javascript based frameworks. It's all about databinding and we're not talking about strings, were talking about client side strong type binding. – JWP Oct 15 '14 at 14:12
  • @user1522548: Please post your concepts in an answer for review as suggested. comments are not appropriate for broader discussions. Thanks. – Gone Coding Oct 15 '14 at 14:15
  • Thanks TrueBlue didn't mean to offend anyone, and am new to the protocol here. – JWP Oct 15 '14 at 14:41
  • 8
    @TomaszZielinski M(MVVM)C – Mohamed Emad Nov 17 '14 at 12:08
  • your blog post kinda resembles Prism's mvvmp – eran otzap Mar 22 '15 at 16:45
  • @eran otzap: do you have a recent reference you can link to? I was working heavily with Prism at the time, but that was so many years ago now. – Gone Coding Mar 22 '15 at 17:20
  • It's like a personal opinion since the presenter holds references to VM(s) . and itself is responsible for populating their properties. (Including hooking up logic to commands exposed by the VM.) So in fact they remain a dumb container holding most of the memory and the presenter creates thous containers aside from wcf proxies and such and conducts logic on the presentation layer. – eran otzap Mar 22 '15 at 19:50
  • @eran otzap: Although I think the OP was asking for answers relating to MVC and *client-side* MVVM, my prior work with Silverlight, WPF (both with PRISM) lead me to consider controllers to always be a required part of the equation. The only time you would not consider it is with really basic MVVM binding like KnockOut which is really only about sharing property changes. – Gone Coding Mar 22 '15 at 20:27
  • I agree , i just compared mvvmp to mvc because i see much similarities between a controller and a presenter , a presenter is a kind of controller which aside from separating the how , he is responsible for updating models / ViewModels which intern affect the view – eran otzap Mar 22 '15 at 22:00
  • @MohamedEmad: I even got further enlightenment as M-C(VM)-V. Here the controller just keeps a view model for the view. Surprisingly enough, this is how I have been coding my angular apps. – Alappin Jul 02 '15 at 03:42
  • @Tomas Zielinski MVVM is a pattern that can be used independently from an MVC application. We use the MVVM pattern with Javascript client side code. Our AJAX calls into MVC patterned Web API. I see them as two distinct patterns with different purposes. They can be used in conjunction with each other but one part does not replace the other. – KeyOfJ Sep 23 '16 at 20:36
  • Blog post/site has Gone Missing. @GoneCoding have you moved it? – khargoosh Aug 15 '20 at 01:06
  • @khargoosh Lost all my hosted domains and content. Had to find a new provider. Will link to the archive on archive.org. Thanks for noticing! :) – Gone Coding Aug 20 '20 at 17:35
303

I think the easiest way to understand what these acronyms are supposed to mean is to forget about them for a moment. Instead, think about the software they originated with, each one of them. It really boils down to just the difference between the early web and the desktop.

As they grew in complexity in the mid-2000s, the MVC software design pattern - which was first described in the 1970s - began to be applied to web applications. Think database, HTML pages, and code inbetween. Let's refine this just a little bit to arrive at MVC: For »database«, let's assume database plus interface code. For »HTML pages«, let's assume HTML templates plus template processing code. For »code inbetween«, let's assume code mapping user clicks to actions, possibly affecting the database, definitely causing another view to be displayed. That's it, at least for the purpose of this comparison.

Let's retain one feature of this web stuff, not as it is today, but as it existed ten years ago, when JavaScript was a lowly, despicable annoyance, which real programmers did well to steer clear of: The HTML page is essentially dumb and passive. The browser is a thin client, or if you will, a poor client. There is no intelligence in the browser. Full page reloads rule. The »view« is generated anew each time around.

Let's remember that this web way, despite being all the rage, was horribly backward compared to the desktop. Desktop apps are fat clients, or rich clients, if you will. (Even a program like Microsoft Word can be thought of as some kind of client, a client for documents.) They're clients full of intelligence, full of knowledge about their data. They're stateful. They cache data they're handling in memory. No such crap as a full page reload.

And this rich desktop way is probably where the second acronym originated, MVVM. Don't be fooled by the letters, by the omission of the C. Controllers are still there. They need to be. Nothing gets removed. We just add one thing: statefulness, data cached on the client (and along with it intelligence to handle that data). That data, essentially a cache on the client, now gets called »ViewModel«. It's what allows rich interactivity. And that's it.

  • MVC = model, controller, view = essentially one-way communication = poor interactivity
  • MVVM = model, controller, cache, view = two-way communication = rich interactivity

We can see that with Flash, Silverlight, and - most importantly - JavaScript, the web has embraced MVVM. Browsers can no longer be legitimately called thin clients. Look at their programmability. Look at their memory consumption. Look at all the Javascript interactivity on modern web pages.

Personally, I find this theory and acronym business easier to understand by looking at what it's referring to in concrete reality. Abstract concepts are useful, especially when demonstrated on concrete matter, so understanding may come full circle.

 

Ben Aston
  • 45,997
  • 54
  • 176
  • 303
Lumi
  • 13,155
  • 7
  • 50
  • 84
  • 54
    MVC did not originate on the web. Trygve Reenskaug introduced MVC into Smalltalk-76 in the 1970s. – Arialdo Martini May 02 '14 at 21:02
  • 12
    Even if it were changed to "MVC was popularized through web application design." I would argue that this is speculation without proper citation. – Dan Bechard May 09 '14 at 13:58
  • 4
    Arialdo: Thanks, I didn't know about Smalltalk-76. (Played with other toys back then. :) Jokes aside, it's interesting how old some of these concepts are. - @Dan, what I wrote is: "[MVC] may have been there before [the web], but the web is how it got popularized to the masses of web developers." I still think that's correct. I don't have a citation for it, but then I don't feel I need one because that MVC mass popularizing is part of my personal experience when I started as a web developer at the beginning of the last decade. Apache Struts was en vogue back then, with lots of beans for MVC. – Lumi May 10 '14 at 07:48
  • 1
    @Lumi I was agreeing with that statement, but it directly conflicts your previous sentence "The first acronym, MVC, originated on the web." which states a web origin as fact. It's like saying "The sky is purple. (Actually the sky is blue, but on rare occasions it has a purple-like hue.)" :P – Dan Bechard May 10 '14 at 13:35
  • 5
    MVC is not "essentially one-way communication" as browsers issue Gets and Posts all the time. Both Gets and Posts can change field values found in the query string. This gives browsers ample opportunity to send information back to the controller. MVC was built on top of HTTP 1.0 which always had two way communication in mind. – JWP Oct 15 '14 at 13:43
  • 18
    Thanks Lumi. This made so much more sense to me than the other answers. Is it correct? I have no idea. But from my perspective it was at least coherent. – gcdev Jun 24 '15 at 14:01
  • 1
    Agree with Arialdo, MVC app types were in the early WinForms visual studio project templates, back when the web was still a green screen dial up – Sentinel Mar 09 '17 at 15:27
  • 3
    Lost me at "MVC, originated on the web". Please don't guess when answering questions. – Cross_ Jul 26 '17 at 17:39
  • 2
    Great explanation and clearer than many others here which get side tracked from directly answering the question. As to those who question whether it was popularized more recently, see: https://books.google.com/ngrams/graph?content=MVC&year_start=1800&year_end=2008&corpus=15&smoothing=3&share=&direct_url=t1%3B%2CMVC%3B%2Cc0 – Scott Buchanan Dec 08 '17 at 14:42
  • A great explanation, thanks! – Darryl Morley Jun 16 '20 at 19:52
  • Thanks, you made my day kind gentleman – Mr Rubix Apr 07 '21 at 20:15
  • @gcdev My guess is he is correct because Vue refers to their object instances as VM (view-models) – I Want Answers Apr 30 '21 at 07:08
178

MVVM Model-View ViewModel is similar to MVC, Model-View Controller

The controller is replaced with a ViewModel. The ViewModel sits below the UI layer. The ViewModel exposes the data and command objects that the view needs. You could think of this as a container object that view goes to get its data and actions from. The ViewModel pulls its data from the model.

Russel East does a blog discussing more in detail Why is MVVM is different from MVC

Just a learner
  • 21,448
  • 45
  • 133
  • 206
TStamper
  • 28,864
  • 10
  • 63
  • 72
  • 89
    The sentence "The controller is replaced with a View Model" is not correct. In MVVM what does the role of the controller is databinding (or binding by convention if you use that). – DaniCE Mar 23 '10 at 09:58
  • 9
    MVVM will only make sense when using WPF's two way data binding. Otherwise MVC/MVP etc would be sufficient. – Jeff Sep 20 '10 at 23:42
  • @Jeff wouldn't MVVM also apply to JavaFX Script? – Sled May 26 '11 at 16:10
  • @ArtB sorry I have no idea about Java. – Jeff May 27 '11 at 15:29
  • 276
    @DaniCE: Josh Smith: `If you put ten software architects into a room and have them discuss what the Model-View-Controller pattern is, you will end up with twelve different opinions. …` – sll Feb 13 '12 at 20:30
  • @DaniCE, correct, have experienced that! However, 10 from them, 11th from yourself, but where does the 12th it come from - just asking! – Om Shankar May 30 '13 at 11:56
  • 8
    @OmShankar The 11th isn't from yourself. There are 10 total people, and 12 total opinions. The adage is meant to imply that the definitions of these patterns is so open to interpretation that at least two people will be confused enough to have more than one opinion. – Dan Bechard May 09 '14 at 13:52
  • 9
    @DaniCE Well this is actually the point of WPF's data binding, and the Microsoft invented MVVM, in that one can bypass the controller completely, (claiming the sentence "The controller is being replaced with a View Model" to be incorrect just because there is a controller behind the scenes, is basically like claiming a statement "Higher level language replace the use of cryptic machine code with more readable ones" to be incorrect because behind the scenes machine language is still being used...) – yoel halb Jul 27 '14 at 06:17
  • @PeterTseng While you are right that in situations like ASP.NET MVC the controller is used to manipulate the view and not the other way around, however the definition of MVC by the gang of four (as quoted in http://blog.iandavis.com/2008/12/09/what-are-the-benefits-of-mvc/) appears to be the other way around as they write "A view uses an instance of a Controller subclass to implement a particular response strategy; to implement a different strategy, simply replace the instance with a different kind of controller", and it is like the business tire in 3 tire application – yoel halb Jul 27 '14 at 06:24
  • @PeterTseng Although in modern terms this definition would more closely match the MVP pattern than what is considered today as the MVC pattern sucha as in ASP.NET MVC, we can still differentiate it from MVP, by saying that in MVC the view is decoupled from the controller, not being a one-by-one relationship, and only ONE of them knows and decides about the other, however whether the view is deciding which controller to use or the controller deciding which view to use is not part of the MVC pattern specification, although I would find more natural say that this decision belongs for controller – yoel halb Jul 27 '14 at 06:27
  • @yo hal Your reply is about a quite old comment. Today I would prefer to say that Model - View - ViewModel is a different pattern from MVC and its components does not match exactly (and has no sense try to match them). If they matched exactly the two patters will be the same and MVVM will not be necessary. – DaniCE Jul 28 '14 at 10:46
  • 1
    Why would the viewmodel replace the controller. The very name of controller indicates it's purpose which is to be a mediator of the View and the View Content, it's a traffic cop and that's all it is. – JWP Oct 15 '14 at 13:37
95

For one thing, MVVM is a progression of the MVC pattern which uses XAML to handle the display. This article outlines some of the facets of the two.

The main thrust of the Model/View/ViewModel architecture seems to be that on top of the data (”the Model”), there’s another layer of non-visual components (”the ViewModel”) that map the concepts of the data more closely to the concepts of the view of the data (”the View”). It’s the ViewModel that the View binds to, not the Model directly.

sll
  • 56,967
  • 21
  • 100
  • 149
Chris Ballance
  • 32,056
  • 25
  • 101
  • 147
  • 21
    I think the paragraph you quoted sums it up nicely IMHO. An aspect of the ViewModel is that it is a flattened/altered version of the model for the view. Many other MV* patterns bind against the *real* model. – Daniel Auger Mar 20 '09 at 21:33
  • 1
    "Many other MV* patterns bind again the real model”? Really? I thought the view was always supposed to bind to the controller in MVC, no matter what. – Debajit Apr 09 '11 at 15:31
  • 9
    Nocturne: In classic MVC, View doesn't have much to do with controller, it binds mostly to Model. Think of it as of a robot - Model represents the position of robot's joints, View is a LCD monitor on which you see the robot, Controller is e.g. keyboard. In such setup, View depends on Model, i.e. the spatial position of robot, that you can see on the monitor is a direct representation of Model. – Tomasz Zieliński Jul 13 '11 at 22:55
  • @Nocturne What daniel appeared to say is that while officially all MV* should use a separate VM, many developers just ignore it, and pass the actual model, and in fact nothing in the specifications for example of MVC disallows it, however in MVVM one must a VM being responsible fot the transition between the model and the view – yoel halb Jul 27 '14 at 06:34
  • I would say it like this: The model is closet thing to DB schema. When a query is run it can project the data into strong types at the model layer. The viewmodel is collections of things, including model objects, but can and does hold view state with respect to the data. The controller is simply a traffic cop between the viewmodel and the view and of course the view is only concerned with view states. – JWP Oct 15 '14 at 13:40
54

Microsoft provided an explanation of the MVVM Pattern in the Windows environment here.

Here's a crucial section:

In the Model-View-ViewModel design pattern, an app is composed of three general components. enter image description here

  • Model: This represents the data model that your app consumes. For example, in a picture sharing app, this layer might represent the set of pictures available on a device and the API used to read and write to the picture library.

  • View: An app typically is composed of multiple pages of UI. Each page shown to the user is a view in MVVM terminology. The view is the XAML code used to define and style what the user sees. The data from the model is displayed to the user, and it’s the job of the ViewModel to feed the UI this data based on the current state of the app. For example, in a picture sharing app, the views would be the UI that show the user the list of albums on the device, the pictures in an album, and perhaps another that shows the user a particular picture.

  • ViewModel: The ViewModel ties the data model, or simply the model, to the UI, or views, of the app. It contains the logic with which to manage the data from the model and exposes the data as a set of properties to which the XAML UI, or views, can bind. For example, in a picture sharing app, the ViewModel would expose a list of albums, and for each album expose a list of pictures. The UI is agnostic of where the pictures come from and how they are retrieved. It simply knows of a set of pictures as exposed by the ViewModel and shows them to the user.

ruffin
  • 13,513
  • 8
  • 72
  • 118
Mat
  • 7,513
  • 4
  • 38
  • 56
  • 7
    Note that while article referenced applies to development with the Microsoft Stack - Specifically Windows Phone - and XAML, it's doesn't have to be. – Richard Nalezynski Nov 08 '16 at 00:47
  • This answer highlights the problem with the name "MVVM" - it should be "VVMM" or "MVMV" - M-V-VM has the relationships completely the wrong way around! – Etherman Mar 25 '19 at 08:43
49

I thought one of the main differences was that in MVC, your V reads your M directly, and goes via the C to manipulate the data, whereas in MVVM, your VM acts as an M proxy, as well as providing the available functionality to you V.

If I'm not full of junk, I'm surprised no one has created a hybrid, where your VM is merely a M proxy, and C provides all functionality.

Rap
  • 6,250
  • 2
  • 45
  • 80
George R
  • 3,284
  • 3
  • 30
  • 36
  • 1
    +1. The term is the correct one i think. but about creating hybrid M-MProxy-V-C isn't that too much separation? i think it would be enough using M-V-C whereas M is a Model with full support of Binding. ;) – ktutnik Aug 24 '10 at 13:14
  • 2
    +1. As I commented above, I think that MVC is used to architect the whole (web) application, while MVVM is used inside View component of MVC. – Tomasz Zieliński Jul 13 '11 at 23:01
  • 23
    @ktutnik: Model usually sits on the server, whereas ViewModel lives on the client. So it's no feasible for HTML to bind directly to server-side Model. Therefore we need ModelView which acts as a local, unsaved working set of data extracted from model using e.g. AJAX/JSON. – Tomasz Zieliński Jul 13 '11 at 23:03
  • 1
    The view does indeed "read" the model data because it's already been put there by the controller. I like to refer to it as a "data injection" by the controller as it's really the controller that is in charge. All the view does in render and fire events in my mind. – JWP Oct 15 '14 at 13:46
  • 3
    I apologize but disagree with the MVVM interpretation. A ViewModel has no idea about a View or what a View will look like or how it will respond and a Model likewise has no idea of a ViewModel. In fact, a View shouldn't even know of a Model either, just a ViewModel. Model should represent data and application state, ViewModel should translate the state to UI capable data (I recommend all primitives at this point) and a View should react to the ViewModels translation. The data will often be the same but it should still be wrapped and re-delivered via a ViewModel and no controllers exist. – Michael Puckett II Jan 25 '17 at 05:25
31

MVC is a controlled environment and MVVM is a reactive environment.

In a controlled environment you should have less code and a common source of logic; which should always live within the controller. However; in the web world MVC easily gets divided into view creation logic and view dynamic logic. Creation lives on the server and dynamic lives on the client. You see this a lot with ASP.NET MVC combined with AngularJS whereas the server will create a View and pass in a Model and send it to the client. The client will then interact with the View in which case AngularJS steps in to as a local controller. Once submitted the Model or a new Model is passed back to the server controller and handled. (Thus the cycle continues and there are a lot of other translations of this handling when working with sockets or AJAX etc but over all the architecture is identical.)

MVVM is a reactive environment meaning you typically write code (such as triggers) that will activate based on some event. In XAML, where MVVM thrives, this is all easily done with the built in databinding framework BUT as mentioned this will work on any system in any View with any programming language. It is not MS specific. The ViewModel fires (usually a property changed event) and the View reacts to it based on whatever triggers you create. This can get technical but the bottom line is the View is stateless and without logic. It simply changes state based on values. Furthermore, ViewModels are stateless with very little logic, and Models are the State with essentially Zero logic as they should only maintain state. I describe this as application state (Model), state translator (ViewModel), and then the visual state / interaction (View).

In an MVC desktop or client side application you should have a Model, and the Model should be used by the Controller. Based on the Model the controller will modify the View. Views are usually tied to Controllers with Interfaces so that the Controller can work with a variety of Views. In ASP.NET the logic for MVC is slightly backwards on the server as the Controller manages the Models and passes the Models to a selected View. The View is then filled with data based on the model and has it's own logic (usually another MVC set such as done with AngularJS). People will argue and get this confused with application MVC and try to do both at which point maintaining the project will eventually become a disaster. ALWAYS put the logic and control in one location when using MVC. DO NOT write View logic in the code behind of the View (or in the View via JS for web) to accommodate Controller or Model data. Let the Controller change the View. The ONLY logic that should live in a View is whatever it takes to create and run via the Interface it's using. An example of this is submitting a username and password. Whether desktop or web page (on client) the Controller should handle the submit process whenever the View fires the Submit action. If done correctly you can always find your way around an MVC web or local app easily.

MVVM is personally my favorite as it's completely reactive. If a Model changes state the ViewModel listens and translates that state and that's it!!! The View is then listening to the ViewModel for state change and it also updates based on the translation from the ViewModel. Some people call it pure MVVM but there's really only one and I don't care how you argue it and it's always Pure MVVM where the View contains absolutely no logic.

Here's a slight example: Let's say the you want to have a menu slide in on a button press. In MVC you will have a MenuPressed action in your interface. The Controller will know when you click the Menu button and then tell the View to slide in the Menu based on another Interface method such as SlideMenuIn. A round trip for what reason? Incase the Controller decides you can't or wants to do something else instead that's why. The Controller should be in charge of the View with the View doing nothing unless the Controller says so. HOWEVER; in MVVM the slide menu in animation should be built in and generic and instead of being told to slide it in will do so based on some value. So it listens to the ViewModel and when the ViewModel says, IsMenuActive = true (or however) the animation for that takes place. Now, with that said I want to make another point REALLY CLEAR and PLEASE pay attention. IsMenuActive is probably BAD MVVM or ViewModel design. When designing a ViewModel you should never assume a View will have any features at all and just pass translated model state. That way if you decide to change your View to remove the Menu and just show the data / options another way, the ViewModel doesn't care. So how would you manage the Menu? When the data makes sense that's how. So, one way to do this is to give the Menu a list of options (probably an array of inner ViewModels). If that list has data, the Menu then knows to open via the trigger, if not then it knows to hide via the trigger. You simply have data for the menu or not in the ViewModel. DO NOT decide to show / hide that data in the ViewModel.. simply translate the state of the Model. This way the View is completely reactive and generic and can be used in many different situations.

All of this probably makes absolutely no sense if you're not already at least slightly familiar with the architecture of each and learning it can be very confusing as you'll find ALOT OF BAD information on the net.

So... things to keep in mind to get this right. Decide up front how to design your application and STICK TO IT.

If you do MVC, which is great, then make sure you Controller is manageable and in full control of your View. If you have a large View consider adding controls to the View that have different Controllers. JUST DON'T cascade those controllers to different controllers. Very frustrating to maintain. Take a moment and design things separately in a way that will work as separate components... And always let the Controller tell the Model to commit or persist storage. The ideal dependency setup for MVC in is View ← Controller → Model or with ASP.NET (don't get me started) Model ← View ↔ Controller → Model (where Model can be the same or a totally different Model from Controller to View) ...of course the only need to know of Controller in View at this point is mostly for endpoint reference to know where back to pass a Model.

If you do MVVM, I bless your kind soul, but take the time to do it RIGHT! Do not use interfaces for one. Let your View decide how it's going to look based on values. Play with the View with Mock data. If you end up having a View that is showing you a Menu (as per the example) even though you didn't want it at the time then GOOD. You're view is working as it should and reacting based on the values as it should. Just add a few more requirements to your trigger to make sure this doesn't happen when the ViewModel is in a particular translated state or command the ViewModel to empty this state. In your ViewModel DO NOT remove this with internal logic either as if you're deciding from there whether or not the View should see it. Remember you can't assume there is a menu or not in the ViewModel. And finally, the Model should just allow you to change and most likely store state. This is where validation and all will occur; for example, if the Model can't modify the state then it will simply flag itself as dirty or something. When the ViewModel realizes this it will translate what's dirty, and the View will then realize this and show some information via another trigger. All data in the View can be binded to the ViewModel so everything can be dynamic only the Model and ViewModel has absolutely no idea about how the View will react to the binding. As a matter of fact the Model has no idea of a ViewModel either. When setting up dependencies they should point like so and only like so View → ViewModel → Model (and a side note here... and this will probably get argued as well but I don't care... DO NOT PASS THE MODEL to the VIEW unless that MODEL is immutable; otherwise wrap it with a proper ViewModel. The View should not see a model period. I give a rats crack what demo you've seen or how you've done it, that's wrong.)

Here's my final tip... Look at a well designed, yet very simple, MVC application and do the same for an MVVM application. One will have more control with limited to zero flexibility while the other will have no control and unlimited flexibility.

A controlled environment is good for managing the entire application from a set of controllers or (a single source) while a reactive environment can be broken up into separate repositories with absolutely no idea of what the rest of the application is doing. Micro managing vs free management.

If I haven't confused you enough try contacting me... I don't mind going over this in full detail with illustration and examples.

At the end of the day we're all programmers and with that anarchy lives within us when coding... So rules will be broken, theories will change, and all of this will end up hog wash... But when working on large projects and on large teams, it really helps to agree on a design pattern and enforce it. One day it will make the small extra steps taken in the beginning become leaps and bounds of savings later.

Michael Puckett II
  • 5,915
  • 5
  • 21
  • 41
  • Amazingly detailed and accurate answer! Made it crystal-clear for me. :-) – ankush981 Dec 15 '18 at 07:26
  • "learning it can be very confusing as you'll find A LOT OF BAD information on the net." Yep. As someone who seems to have a lot of experience with these design patterns, do you know of any good tutorials/guides? – MarredCheese Mar 15 '19 at 19:53
  • 1
    To be honest, my MVVM knowledge has been through years or trial and error and using / doing it various ways based on team efforts. I recently (2 years ago) was able to put my own experience into a summarized game plan and lead a team start to finish doing so and we were extremely successful. That said, I can't point you into any one spot and apologize. I can say that you are correct, because of the various opinions it is very confusing but, IMO, with MVVM it's to be as generic as possible. Make ViewModels capable of allowing views to bind and work with data strictly but for ANY view... – Michael Puckett II Mar 18 '19 at 19:38
  • 1
    In other words NEVER make the ViewModel assume a View will look or act in any way. ViewModel, to me, are best used like an API, but with strict communication. Follow the game plan for binding, editing, commanding, etc. If the View needs extra logic to function a specific way, that has nothing to do with the app or data (such as an animation or a dropdown box..) then that logic belongs in the View tier somewhere somehow. Again, there's a plethora of opinions and this is just mine but I have a strong background here and a solid track record so far. – Michael Puckett II Mar 18 '19 at 19:42
  • I have example apps that I don't mind sharing and or wouldn't mind setting up a simple show and tell for you or anyone else if wanted or curious. – Michael Puckett II Mar 18 '19 at 19:44
  • @MichaelPuckettII Hi, would you mind to share your example apps? I'm at the beginning to learn MVVM and really want to learn from you, how I could contact you? thanks – Sukma Wardana Mar 28 '19 at 21:39
  • No problem, michael_puckett_ii@hotmail.com – Michael Puckett II Mar 28 '19 at 21:42
27

Simple Difference: (Inspired by Yaakov's Coursera AngularJS course)

enter image description here

MVC (Model View Controller)

  1. Models: Models contain data information. Does not call or use Controller and View. Contains the business logic and ways to represent data. Some of this data, in some form, may be displayed in the view. It can also contain logic to retrieve the data from some source.
  2. Controller: Acts as the connection between view and model. View calls Controller and Controller calls the model. It basically informs the model and/or the view to change as appropriate.
  3. View: Deals with UI part. Interacts with the user.

MVVM (Model View View Model)

ViewModel:

  1. It is the representation of the state of the view.
  2. It holds the data that’s displayed in the view.
  3. Responds to view events, aka presentation logic.
  4. Calls other functionalities for business logic processing.
  5. Never directly asks the view to display anything.
Pritam Banerjee
  • 15,297
  • 10
  • 71
  • 92
21

The other answers might not be easy to understand for one who is not much familiar with the subject of architectural patterns. Someone who is new to app architecture might want to know how its choice can affect her app in practice and what all the fuss is about in communities.

Trying to shed some light on the above, I made up this screenplay involving MVVM, MVP and MVC. The story begins by a user clicking on the ‘FIND’ button in a movie search app… :

User: Click …

View: Who’s that? [MVVM|MVP|MVC]

User: I just clicked on the search button …

View: Ok, hold on a sec … . [MVVM|MVP|MVC]

( View calling the ViewModel|Presenter|Controller … ) [MVVM|MVP|MVC]

View: Hey ViewModel|Presenter|Controller, a User has just clicked on the search button, what shall I do? [MVVM|MVP|MVC]

ViewModel|Presenter|Controller: Hey View, is there any search term on that page? [MVVM|MVP|MVC]

View: Yes,… here it is … “piano” [MVVM|MVP|MVC]

—— This is the most important difference between MVVM AND MVP|MVC ———

Presenter|Controller: Thanks View,… meanwhile I’m looking up the search term on the Model, please show him/her a progress bar [MVP|MVC]

( Presenter|Controller is calling the Model … ) [MVP|MVC]

ViewModel: Thanks, I’ll be looking up the search term on the Model but will not update you directly. Instead, I will trigger events to searchResultsListObservable if there is any result. So you had better observe on that. [MVVM]

(While observing on any trigger in searchResultsListObservable, the View thinks it should show some progress bar to the user, since ViewModel would not talk to it on that)

——————————————————————————————

ViewModel|Presenter|Controller: Hey Model, Do you have any match for this search term?: “piano” [MVVM|MVP|MVC]

Model: Hey ViewModel|Presenter|Controller, let me check … [MVVM|MVP|MVC]

( Model is making a query to the movie database … ) [MVVM|MVP|MVC]

( After a while … )

———— This is the diverging point between MVVM, MVP and MVC ————–

Model: I found a list for you, ViewModel|Presenter, here it is in JSON “[{“name”:”Piano Teacher”,”year”:2001},{“name”:”Piano”,”year”:1993}]” [MVVM|MVP]

Model: There is some result available, Controller. I have created a field variable in my instance and filled it with the result. It’s name is “searchResultsList” [MVC]

(Presenter|Controller thanks Model and gets back to the View) [MVP|MVC]

Presenter: Thanks for waiting View, I found a list of matching results for you and arranged them in a presentable format: [“Piano Teacher 2001″,”Piano 1993”]. Also please hide the progress bar now [MVP]

Controller: Thanks for waiting View, I have asked Model about your search query. It says it has found a list of matching results and stored them in a variable named “searchResultsList” inside its instance. You can get it from there. Also please hide the progress bar now [MVC]

ViewModel: Any observer on searchResultsListObservable be notified that there is this new list in presentable format: [“Piano Teacher 2001″,”Piano 1993”].[MVVM]

View: Thank you very much Presenter [MVP]

View: Thank you “Controller” [MVC] (Now the View is questioning itself: How should I present the results I get from the Model to the user? Should the production year of the movie come first or last…?)

View: Oh, there is a new trigger in searchResultsListObservable … , good, there is a presentable list, now I only have to show it in a list. I should also hide the progress bar now that I have the result. [MVVM]

In case you are interested, I have written a series of articles here, comparing MVVM, MVP and MVC by implementing a movie search android app.

Holmes Queen
  • 292
  • 1
  • 4
  • 16
Ali Nem
  • 4,220
  • 1
  • 38
  • 36
  • 1
    There's a great answer under all the flavor text here... With some formatting and throwing out small talk between components this could be the best one on this page. – neonblitzer Mar 13 '20 at 21:00
  • 1
    Well explained and highlights underlying difference between MVC and MVVM – Kedar Jun 19 '20 at 18:18
19

MVVM is a refinement (debatable) of the Presentation Model pattern. I say debatable, because the only difference is in how WPF provides the ability to do data binding and command handling.

wekempf
  • 2,691
  • 14
  • 15
  • 1
    In 2009 this answer was probably a good one but today, there is no debate as even HTML Helper controls from MSFT allow for binding using the infamous "For" helpers. Knockout is all about data-binding on the client side. – JWP Oct 15 '14 at 13:47
  • 1
    I stated this, in 2009, because far too many people in the community accepted this answer. I said it was debatable, because MVVM and Presentation Model really are the same pattern by different names. Tanks to the popularity in WPF, it's often called MVVM in other frameworks today, but either name is accurate. – wekempf Jul 26 '17 at 20:16
16

The viewmodel is an "abstract" model for your user interface elements. It must allow you to execute the commands, and actions in your view in a non-visual way (for example to test it).

If you have worked with MVC, you probably have sometime found useful to create model objects to reflect the state of your view, for example, to show and hide some edit dialog, etc. In that case you are using a viewmodel.

The MVVM pattern is simply the generalization of that practice to all the UI elements.

And it's not a Microsoft pattern, what appends is that WPF / Silverlight data-bindings are specially well-suited to work with this pattern. But nothing stops you to use it with java server faces, for example.

DaniCE
  • 2,322
  • 1
  • 16
  • 25
12

It surprises me that this is a highly voted answers without mentioning the origin of MVVM. MVVM is a popular term used in Microsoft community and it is originated from Martin Fowler's Presentation Model. So to understand the motive of the pattern and the differences with others, the original article about the pattern is the first thing to read.

Cheng
  • 542
  • 8
  • 12
  • Wow...so both MVC and MVVM came from SmallTalk?? They were way ahead of their time apparently... – MattE Oct 19 '16 at 04:22
  • Actually, saying it originated from Martin Fowler's Presentation Model isn't accurate. It's very difficult to determine which came first, but both patterns (allowing that they are really the same pattern) were arrived at independently and at roughly the same time. – wekempf Jul 26 '17 at 20:13
10

Injecting Strongly Typed ViewModels into the View using MVC

  1. The controller is responsible for newing up the ViewModel and injecting it into the View. (for get requests)
  2. The ViewModel is the container for DataContext and view state such as the last selected item etc.
  3. The Model contains DB entities and is very close to the DB Schema it does the queries and filtering. (I like EF and LINQ for this)
  4. The Model should also consider repositories and or projection of results into strong types (EF has a great method... EF.Database.Select(querystring, parms) for direct ADO access to inject queries and get back strong types. This addresses the EF is slow argument. EF is NOT SLOW!
  5. The ViewModel gets the data and does the business rules and validation
  6. The controller on post back will cal the ViewModel Post method and wait for results.
  7. The controller will inject the newly updated Viewmodel to the View. The View uses only strong type binding.
  8. The view merely renders the data, and posts events back to the controller. (see examples below)
  9. MVC intercepts the inbound request and routes it to proper controller with strong data type

In this model there is no more HTTP level contact with the request or response objects as MSFT's MVC machine hides it from us.

In clarification of item 6 above (by request)...

Assume a ViewModel like this:

public class myViewModel{
     public string SelectedValue {get;set;}
public void Post(){
    //due to MVC model binding the SelectedValue string above will be set by MVC model binding on post back.
    //this allows you to do something with it.
    DoSomeThingWith(SelectedValue);
    SelectedValue = "Thanks for update!";
 }
}

The controller method of the post will look like this (See below), note that the instance of mvm is automatically instanciated by the MVC binding mechanisms. You never have to drop down to the query string layer as a result! This is MVC instantiating the ViewModel for you based on the query strings!

[HTTPPOST]   
public ActionResult MyPostBackMethod (myViewModel mvm){
         if (ModelState.IsValid)
        {
               // Immediately call the only method needed in VM...
               mvm.Post()
        }
      return View(mvm);
}

Note that in order for this actionmethod above to work as you intend, you must have a null CTOR defined that intializes things not returned in the post. The post back must also post back name/value pairs for those things which changed. If there are missing name/value pairs the MVC binding engine does the proper thing which is simply nothing! If this happens you might find yourself saying "I'm losing data on post backs"...

The advantage of this pattern is the ViewModel does all the "clutter" work interfacing to the Model/Buisness logic, the controller is merely a router of sorts. It is SOC in action.

Community
  • 1
  • 1
JWP
  • 5,969
  • 3
  • 39
  • 65
  • Can you clarify item 6? I realises you are covering ASP.Net only, but it appears to be adding an unwanted dependency to the ViewModel. (e.g. knowledge of where the data comes from/goes to). A code (pseudo-code?) example would be good to clarify this answer and show which parts are server-side and which are client-side. – Gone Coding Apr 29 '15 at 08:46
9

From what I can tell, the MVVM maps to the MV of MVC - meaning that in a traditional MVC pattern the V does not communicate directly with the M. In the second version of MVC, there is a direct link between M and V. MVVM appears to take all tasks related to M and V communication, and couple it to decouple it from the C. In effect, there's still the larger scope application workflow (or implementation of the use scenarios) that are not fully accounted for in MVVM. This is the role of the controller. By removing these lower level aspects from the controllers, they are cleaner and makes it easier to modify the application's use scenario and business logic, also making controllers more reusable.

se_thoughts
  • 91
  • 1
  • 1
  • 1
    IMHO I would argue that "making controllers more reusable" is too broad a statement and counter-productive for general ASP.Net "controllers" (i.e. not the business logic layer) as those controllers typically contain the parts of the application that are *application-specific*. It is the Views, Models, ViewModels and business logic that need to be reusable. I would have thought treating the business logic modules as service providers, not as controllers, would be a better option. – Gone Coding Apr 29 '15 at 08:52
  • But you are talking about the "ViewModel" in Asp.net, not about the MVVM design pattern. Two different things. – Luis Apr 27 '18 at 16:26
9

MVVM adds the view model into the mix. This is important, as it allows you to use a lot of the binding approach of WPF, without putting all that UI specific pieces in your regular model.

I may be wrong, but I am not sure MVVM really forces the controller into the mix. I find the concept to be more in line with: http://martinfowler.com/eaaDev/PresentationModel.html. I think that people choose to combine it with MVC, not that it is built in into the pattern.

eglasius
  • 34,909
  • 4
  • 58
  • 105
  • 3
    MVVM, strictly speaking, is Presentation Model, though MVVM is becoming the preferred name for the WPF specific realization of the pattern. – wekempf Mar 27 '09 at 21:26
  • Agreed. The Viewmodel in MVC "IS" the state machine for the view. It contains the datacontext and tracks all selected item information as well as can contain all validation logic using the IValidatableObject interface. The ViewModel interfaces with the DB at the model layer which can use strong typed models. MVVM in WPF IS the controller of MVC. But the controller of MVC is much cleaner, it is essential a routing handler. – JWP Oct 15 '14 at 13:51
6

Well, generally MVC is used in Web development and MVVM is most popular in WPF/Silverlight development. However, sometimes the web architecute might have a mix of MVC and MVVM.

For example: you might use knockout.js and in this case you will have MVVM on your client side. And your MVC's server side can also change. In the complex apps, nobody uses the pure Model. It might have a sense to use a ViewModel as a "Model" of MVC and your real Model basically will be a part of this VM. This gives you an extra abstraction layer.

Nishu Tayal
  • 18,079
  • 8
  • 44
  • 90
6

The Controller is not replaced by a ViewModel in MVVM, because the ViewModel has a totally different functionality then a Controller. You still need a Controller, because without a Controller your Model, ViewModel and View will not do much... In MVVM you have a Controller too, the name MVVM is just missleading.

MVVMC is the correct name in my humble opinion.

As you can see the ViewModel is just an addition to the MVC pattern. It moves conversion-logic (for example convert object to a string) from the Controller to the ViewModel.

Ini
  • 383
  • 5
  • 16
6

MVVM

  1. View ➡ ViewModel ➡ Model
  • The view has a reference to the ViewModel but not vice versa.
  • The ViewModel has a reference to the Model but not vice versa.
  • The View has no reference to the Model and vice versa.
  1. If you are using a controller, it can have a reference to Views and ViewModels, though a Controller is not always necessary as demonstrated in SwiftUI.
  2. Data Binding: we create listeners for ViewModel Properties so that data can flow from the view to the model through the view model. While the references go one way: View ➡ ViewModel ➡ Model, data needs to flow: View ↔ ViewModel ↔ Model. Its clear how the view gets data from the model, by reading its own properties. Data Binding is how to detect events within the view and feed them back to the model.
class CustomView: UIView {
  var viewModel = MyViewModel {
    didSet {
      self.color = viewModel.viewColor
    }
  }

  convenience init(viewModel: MyViewModel) {
    self.viewModel = viewModel
  }
}


struct MyViewModel {
   var viewColor: UIColor {
      didSet {
         colorChanged?() // This is where the binding magic happens.
      }
   }
   
   var colorChanged: ((UIColor) -> Void)?
}


class MyViewController: UIViewController {

   let myViewModel = MyViewModel(viewColor: .green)
   let customView: CustomView!

   override func viewDidLoad() {
      super.viewDidLoad()

      // This is where the binder is assigned.
      myViewModel.colorChanged = { [weak self] color in 
        print("wow the color changed")
      }
      customView = CustomView(viewModel: myViewModel)
      self.view = customView
   }
}

differences in setup

  1. Business logic is held in the controller for MVC and the ViewModels for MVVM.
  2. Events are passed directly from the View to the controller in MVC while events are passed from the View to the ViewModel to the Controller (if there is one) for MVVM.

Common features

  1. Both MVVM and MVC do not allow the View to send messages directly to the Model/s.
  2. Both have models.
  3. Both have views.

Advantages of MVVM

  1. Because the ViewModels hold business logic, they are smaller concrete objects making them easy to unit tests. On the other hand, in MVC, the business logic is in the ViewController. How can you trust that a unit test of a view controller is comprehensively safe without testing all the methods and listeners simultaneously? You can't wholly trust the unit test results.
  2. In MVVM, because business logic is siphoned out of the Controller into atomic ViewModel units, the size of the ViewController shrinks and this makes the ViewController code more legible.

Advantages of MVC

  1. Providing business logic within the controller reduces the need for branching and therefore statements are more likely to run on the cache which is more performant over encapsulating business logic into ViewModels.
  2. Providing business logic in one place can accelerate the development process for simple applications, where tests are not required. I don't know when tests are not required.
  3. Providing business logic in the ViewController is easier to think about for new developers.
ScottyBlades
  • 7,536
  • 2
  • 50
  • 60
4

MVVMC, or perhaps MVC+, seems to be a viable approach for enterprise as well as rapid application development. While it is nice to separate the UI from business and interaction logic, the 'pure' MVVM pattern and most available examples work best on singular views.

Not sure about your designs, but most of my applications, however, contain pages and several (reusable) views and thus the ViewModels do need to interact to some degree. Using the page as controller would defeat the purpose of the MVVM altogether, so not using a "VM-C" approach for the underlying logic might result in .. well .. challenging constructs as the application matures. Even in VB-6 most of us probably stopped coding business logic into the Button event and started 'relaying' commands to a controller, right? I recently looked at many emerging framworks on that topic; my favorite clearly is the Magellan (at codeplex) approach. Happy coding!

http://en.wikipedia.org/wiki/Model_View_ViewModel#References

der Martin
  • 51
  • 1
3

In very short - in MVC Controler is aware of (controls) view, while in MVVM, ViewModel is unaware of who consumes it. ViewModel exposes its observable properties and actions to whoever might be interested in using it. That fact makes testing easier since there is no reference to UI within ViewModel.

daneejela
  • 8,695
  • 6
  • 29
  • 40
2

From a practical point of view, MVC (Model-View-Controller) is a pattern. However, MVC when used as ASP.net MVC, when combined with Entity Framework (EF) and the "power tools" is a very powerful, partially automated approach for bringing databases, tables, and columns to a web-page, for either full CRUD operations or R (Retrieve or Read) operations only. At least as I used MVVM, the View Models interacted with models that depended upon business objects, which were in turn "hand-made" and after a lot of effort, one was lucky to get models as good as what EF gives one "out-of-the-box". From a practical programming point of view, MVC seems a good choice because it gives one lots of utility out-of-box, but there is still a potential for bells-and-whistles to be added.

JosephDoggie
  • 1,320
  • 3
  • 19
  • 44
2

Complementary to many of the responses given, I wanted to add some additional perspective from the Modern client-side web - or Rich Web Application point of view.

Indeed these days simple web sites and larger web applications are commonly built with many popular libraries such as Bootstrap. Built by Steve Sanderson, Knockout provides support for the MVVM pattern which mimics one of the most important behaviors in the pattern: data-binding through the View Model. With a little JavaScript, data and logic can be implemented that can then be added to page elements with simple data-bind HTML attributes, similar to using many of the features of Bootstrap. Together, these two libraries alone offer interactive content; and when combined with routing this approach can result in a simple-yet-powerful approach to building the Single Page Application.

Similarly, a Modern client-side framework such as Angular follows the MVC pattern by convention, but also adds a Service. Interestingly, it is touted as Model-View-Whatever (MVW). (See this post on Stack Overflow.)

Additionally, with the rise of Progressive web frameworks such as Angular 2, we're seeing a change in terminology and perhaps a new architectural pattern where Components comprise of a View or Template and interact with a Service - all of which can be contained in a Module; and a series of Modules makes up the application.

Community
  • 1
  • 1
2

I used to think that MVC and MVVM are the same. Now because of the existence of Flux I can tell the difference:

In MVC, for each view in your app, you have a model and a controller, so I would call it view, view model, view controller. The pattern does not tell you how one view can communicate with another. Therefore, in different frameworks there are different implementations for that. For example there are implementations where controllers talk to each other whereas in other implementations there's another component that mediates between them. There are even implementations in which the view models communicate with each other, which is a break of the MVC pattern because the view model should only be accessed by the view controller.

In MVVM, you also have a view model for each component. The pattern does not specify how the heck the view should influence the view model, so usually most frameworks just include controller's functionality in the view model. However, MVVM does tell you that your view model's data should come from the model, which is the entire model that's not aware or custom to a specific view.

To demonstrate the difference, let's take Flux pattern. Flux pattern tells how different views in the app should communicate. Each view listens to a store and fires actions using the dispatcher. The dispatcher in turn tells all the stores about the action that was just made, and the stores update themselves. A store in Flux corresponds to the (general) model in MVVM. it's not custom to any specific view. So usually when people use React and Flux, each React component actually implements the MVVM pattern. When an action occurs, the view model calls the dispatcher, and finally it's getting updated according to the changes in the store, which is the model. You can't say that each component implements MVC because in MVC only the controller can update the view model. So MVVM can work with Flux together (MVVM handles the communication between the view and the view model, and Flux handles the communication between different views), whereas MVC can't work with Flux without breaking a key principle.

Alon
  • 5,402
  • 14
  • 64
  • 116
2

mvc is server-side and mvvm is client-side(browser) in web development.

most of the time javascript is used for mvvm in browser. there are many server side technologies for mvc.

Maulik
  • 2,281
  • 1
  • 18
  • 25
1

Model–View–Controller (usually known as MVC) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted by the user. Following the MVC architectural pattern decouples these major components allowing for code reuse and parallel development.

Traditionally used for desktop graphical user interfaces (GUIs), this pattern has become popular for designing web applications. Popular programming languages like JavaScript, Python, Ruby, PHP, Java, and C# have MVC frameworks that are used in web application development straight out of the box.

Model

The central component of the pattern. It is the application's dynamic data structure, independent of the user interface. It directly manages the data, logic, and rules of the application.

View

Any representation of information such as a chart, diagram or table. Multiple views of the same information are possible, such as a bar chart for management and a tabular view for accountants.

Controller

Accepts input and converts it to commands for the model or view.

In addition to dividing the application into these components, the model–view–controller design defines the interactions between them.

The model is responsible for managing the data of the application. It receives user input from the controller.

The view means a presentation of the model in a particular format.

The controller responds to the user input and performs interactions on the data model objects. The controller receives the input, optionally validates it and then passes the input to the model. enter image description here

Model–View–ViewModel (MVVM) is a software architectural pattern.

MVVM facilitates a separation of development of the graphical user interface – be it via a markup language or GUI code – from the development of the business logic or back-end logic (the data model). The view model of MVVM is a value converter, meaning the view model is responsible for exposing (converting) the data objects from the model in such a way that objects are easily managed and presented. In this respect, the view model is more model than a view and handles most if not all of the view's display logic. The view model may implement a mediator pattern, organizing access to the back-end logic around the set of use cases supported by the view.

MVVM is a variation of Martin Fowler's Presentation Model design pattern. MVVM abstracts a view's state and behavior in the same way, but a Presentation Model abstracts a view (creates a view model) in a manner not dependent on a specific user-interface platform.

MVVM was invented by Microsoft architects Ken Cooper and Ted Peters specifically to simplify event-driven programming of user interfaces. The pattern was incorporated into Windows Presentation Foundation (WPF) (Microsoft's .NET graphics system) and Silverlight (WPF's Internet application derivative). John Gossman, one of Microsoft's WPF and Silverlight architects, announced MVVM on his blog in 2005.

Model–View–ViewModel is also referred to as model–view–binder, especially in implementations not involving the .NET platform. ZK (a web application framework written in Java) and KnockoutJS (a JavaScript library) use model–view–binder. enter image description here

Rahul
  • 2,374
  • 2
  • 22
  • 36