ChatGPT解决这个技术问题 Extra ChatGPT

What is the difference between MVC and MVVM? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 2 years ago. Improve this question

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

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.
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.
Such an upvoted question on high-level [design patterns]. I would kindly like to suggest the use of diagrams on the answers.
Here's an archived version of Joel's article: web.archive.org/web/20150219153055/http://joel.inpointform.net/…
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. hackernoon.com/…

L
Laurel

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.


@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.
I agree. My comment was caused by sudden enlightement and not because I disagreed with you.
We also used controllers to control the "flow" of views in a wizard-like UI.
@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.
@TomaszZielinski M(MVVM)C
B
Ben Aston

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.


MVC did not originate on the web. Trygve Reenskaug introduced MVC into Smalltalk-76 in the 1970s.
Even if it were changed to "MVC was popularized through web application design." I would argue that this is speculation without proper citation.
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.
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.
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.
J
Just a learner

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


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).
MVVM will only make sense when using WPF's two way data binding. Otherwise MVC/MVP etc would be sufficient.
@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. …
@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.
@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...)
s
sll

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.


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.
"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.
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.
@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
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.
r
ruffin

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. 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.


Note that while article referenced applies to development with the Microsoft Stack - Specifically Windows Phone - and XAML, it's doesn't have to be.
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!
R
Rap

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.


+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. ;)
+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.
@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.
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.
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.
M
Michael Puckett II

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.


Amazingly detailed and accurate answer! Made it crystal-clear for me. :-)
"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?
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...
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.
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.
P
Pritam Banerjee

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

https://i.stack.imgur.com/zoL2x.png

MVC (Model View Controller)

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. 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. View: Deals with UI part. Interacts with the user.

MVVM (Model View View Model)

ViewModel:

It is the representation of the state of the view. It holds the data that’s displayed in the view. Responds to view events, aka presentation logic. Calls other functionalities for business logic processing. Never directly asks the view to display anything.


R
Ray Jasson

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.


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.
Well explained and highlights underlying difference between MVC and MVVM
The best explanation I've found so far!
w
wekempf

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.


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.
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.
D
DaniCE

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.


C
Cheng

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.


Wow...so both MVC and MVVM came from SmallTalk?? They were way ahead of their time apparently...
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.
C
Community

Injecting Strongly Typed ViewModels into the View using MVC

The controller is responsible for newing up the ViewModel and injecting it into the View. (for get requests) The ViewModel is the container for DataContext and view state such as the last selected item etc. 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) 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! The ViewModel gets the data and does the business rules and validation The controller on post back will cal the ViewModel Post method and wait for results. The controller will inject the newly updated Viewmodel to the View. The View uses only strong type binding. The view merely renders the data, and posts events back to the controller. (see examples below) 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.


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.
e
eglasius

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.


MVVM, strictly speaking, is Presentation Model, though MVVM is becoming the preferred name for the WPF specific realization of the pattern.
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.
s
se_thoughts

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.


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.
But you are talking about the "ViewModel" in Asp.net, not about the MVVM design pattern. Two different things.
S
ScottyBlades

MVVM

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.

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. 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

Business logic is held in the controller for MVC and the ViewModels for MVVM. 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

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

Advantages of MVVM

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. 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

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. 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. Providing business logic in the ViewController is easier to think about for new developers.


Best explanation
N
Nishu Tayal

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.


What 'web development' terms 'MVC' is nothing more than separation of concerns and not the authentic MVC that preceded the web.
d
daneejela

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.


I
Ini

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.


d
der Martin

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


R
Rahul

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.

https://i.stack.imgur.com/munxk.png

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.

https://i.stack.imgur.com/guQtb.png


J
JosephDoggie

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.


A
Alon

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.


M
Maulik

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.


C
Community

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.