Updating Controls from Multiple Pages on Windows Phone - windows-phone-7

All, I am new to Windows 7 Phone. My situation is that I have a main page which contains a ScrollViewer which in turn houses a StackPanel. I want to populate this StackPanel with multiple sub-StackPanels (at runtime) which are to hold an Image Thumb nail a hyperlink and some basic information about the image.
This is all good when I do this from the main page, but I want to know how to update this control (which is on the main page), but from any page other than the main page. I would like to know what is considered best practice for updating a page's control (like that outlined above) from another page.
Obviously there are a number of ways to pass data between pages
PhoneApplicationService.Current.State["yourparam"] = param
NavigationService.Navigate(new Uri("/view/Page.xaml", UriKind.Relative));
then in other page simply
var k = PhoneApplicationService.Current.State["yourparam"];
and many others. But what is best practice for updating a generic control from a different page?
Note: There are many question about data access and passing between pages.
Passing data from page to page
How to pass the image value in one xaml page to another xaml page in windows phone 7?
Passing image from one page to another windows phone 7
and more. This is not what I am asking.

If I understand your question correctly, you are trying to update a control which is on for example MainPage.xaml from another page for example Page2.xaml.
As far as I know there is no way to reach a pages controls from another page, and that seems unnecessary for the cases that I can think of.
The method used to achieve what you are trying is usually done by triggering an action (like the press of a button ) and passing a parameter to the page you are trying to update the control. And on that page's onnavigatedto event (or viewmodel constructor if you are using the MVVM pattern), update your control based on the passed parameter.
If your update is based on data then the best practice is to bind an observable collection or an object that extends the INotifyPropertyChanged (basically any object that can signal that one of their property changed to the ui) and change the data based on the parameter that is passed.
If these two pages somehow are visible at the same time and there is no navigation needed between them( like a popup or sliding menu kind of ui) then you can make the page that you are showing in the popup a usercontrol, and reach to the parent's controls by this.Parent.
I can be more helpful if you give more specifics about your app's flow.

The MVVM pattern would be a good way to go. Saying MVVM is too complicated for small teams isn't exactly accurate - the purpose of MVVM is to decouple Silverlight or WPF code. Using the codebehind of a Silverlight page to directly access data creates coupling in your code and accrues technical debt. Whether you're one developer or 100, if your UI is coupled with your data classes, if you have to change your data classes, you will have to make changes to every UI element that uses those classes. This takes longer and makes your application more difficult to change.
MVVM makes it so your UI (the View) doesn't know anything about the data (your Model). The ViewModel is the code in between that the UI can bind to, and which manages events in the UI that need to be persisted to the Model, and also changes in the Model that need to be represented in the View. For this reason, it handles events, and that's what it sounds like you need in your code - an event that can exist off of the codebehind, that can update the Views bound to it when the data changes. If you have two pages, then an event on one of the pages will be sent to the ViewModel, which will make a change to the Model (data) if necessary, and pass it back to the ViewModel. The ViewModel would then update any of the UI elements (Views) bound to that piece of data.
There's a REALLY good demonstration of how to implement the MVVM design pattern here
. The guy goes through and takes a typical WPF application (just like Silverlight), where the UI codebehind implements event handlers that directly access data, and refactors it using the MVVM pattern.

Related

Wicket - Save current layout / view

I have an application in which I would like the user to 'save the view'. I.e. I make heavy use of ajax to replace all kinds of Panel and use nested jQuery UI Layout plugin for 'frames'.
So basically, the view is defined as the (functional) tree of components, combined with the Javascript state of the jquery plugin, combined with the 'query' a user has given.
I'm wondering what would be a good strategy to save this view state, and how to load it again.
I though of keeping a sort of UIState-model on the page level, and pass it to all components. The components then use specific settings of this model to initialize themselves and changes in the components should be reflected back into this state model.
However, this gets complicated when a Panel is reused in several places. The reason is that a component needs, besides its knowing how to read its own state from the central modal, also take into account the location in the (functional) hierarchy of components.
What would be a good approach? Has anyone done something similar?

How to Handle Mutiple Model Bound Forms

I am buiding a UI screen for editing the details of an Ecommerce Order. The model for my view (OrderModel) has everything I need (in properties that are also ViewModels), but the UI isn't designed to be able to edit all of it at once.
For example, one part of the UI is for customer data..another for order details, and another for tracking information, each having their own "Save" buttons.
I realize that I could use one giant form and use hidden form fields to populate the non-editable fields, making each "Save" button post all the data, but that smells bad.
I'd like to segment the editable chunks into smaller ViewModels that are posted and validated individually while retaining the strong typing but I'm unsure of how to achieve this in MVC3. Will I need partial views that are called from the primary view?
FYI, I'm using ASP.NET MVC 3 with Razor syntax and client side FluentValidation.
Partial Views are a good solution. You can pass different ViewModels to each partial view. But if only sections of the overall view are updated at a time I would not do a post back on the whole page. Instead I would use Ajax calls using JQuery/Javascript to update the individual information back to the controller. I would also look into something like Knockout.js to handle the data binding on the page.

Using PhoneApplicationPage as a nested view container

In MVVM Light toolkit for Windows Phone, whenever I am to add a new MvvmLightView (WP) item, I end up with the template creating a PhoneApplicationPage for me.
What about cases, when I want to create a nested view, for example in case of a ListBox ItemTemplate view.
Before MVVM Light, every time I needed a view to separate markup to, I would have created a standard UserControl and that worked fine.
Should I only use MvvmLightView whenever creating a navigable pages?
The item template is a guidance, that produces some code for you. It is not, nor does it intend to be, the single way of creating views or sub views.
In the case you are mentioning, it is usual to create a user control hat is backed on its own view model. This sub-view view model is then included as a property in your main view model. To pass it to your sub-view (e.g. a user control) you bind this property to the user control's DataContext.
<ext:MyUserControl DataContext="{Binding MySubViewProperty}"/>
However, you do not need a separate view model, in some cases it is more appropriate to share the main view model. In this case you do not need to do the above binding, as it is do one implicitly. Also, when you are using the user control within an DataTemplate the templates DataContext is passed to the user control implicitly and you do not need the binding. In general you only need to set the data context when you want to bind to a property of the current context, or to another context.
MVVM is about freedom and MVVM Light about supporting the developer in using this freedom. All guidance are best practises and provide usually the easiest an/or most consistant way, but nothing stops you going down another route for a good reason. Especially the templates are just shortcuts that provide for one problem, but not for the general (meaning every) case.

How many view models for a panorama page

I'm starting to play with the windows phone 7 panorama control.
I looked at the panorama project template provided in visual studio and saw that the two panorama items use the same view model (and in fact the same data from the model).
How is it in real world applications? Should I best use one view model per panorama item or is it best practice to have only one view model for the complete panorama?
I think that is one View Model per page (a panorama is just a control, not multiple pages). So one ViewModel on a page and every PanoramaItem will use it (My opinion).
It depends on what you are doing.
In most cases I would have separate view models for each page, but if for instance each page is very simple then you may not need it.
An example could be a panorama with each page displaying an image. In this case you might get away with binding the the panorama control to a single list of images.
It really depends on the application. What you saw in the default template is simply there to show you the basics of a MVVM-based design. I personally use a ViewModel for a set of pages that have a similar purpose (e.g. managing media content). There is a single ViewModel locator (per application) that ties them all together.
Bottom line - it is more of a question of preference, as long as the concerns are separated.

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 3 years ago.
Improve this question
Is there a difference between the standard "Model View Controller" pattern and Microsoft's Model/View/ViewModel pattern?
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.
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.
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
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.
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.
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.
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.
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.
Simple Difference: (Inspired by Yaakov's Coursera AngularJS course)
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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.

Resources