14 Days Free Technical Video Training from WintellectNOW

  

Comparing the MVC and MVVM patterns along with their respective ViewModels.

Tags: ASP.NET MVC, MVC, MVVM, SilverLight, WPF, Patterns

It won't take long in your quest to find more information on ASP.NET MVC through internet searches, with bing.com of course, before you'll stumble across the notion of a ViewModel. Mixed within those search results are links to articles on ViewModels in Silverlight/WPF, or other technologies that also use the MVC or MVVM patterns or ViewModels, which can be quite confusing. Having said that, it's no wonder in every presentation I give concerning MVC or ViewModels, a few folks frequently ask these two, quite reasonable, questions: 

  1. "What's the difference between MVC and MVVM ?" (in general)
  2. "What's the difference between ViewModels in MVC and ViewModels in MVVM?"

The elevator pitch: MVC is a web UI pattern, and ASP.NET MVC is Microsoft's implementation of it. MVVM is Microsoft's implementation of a desktop UI pattern in WinForms, SilverLight or WPF.

MVC is an old pattern, in use for decades in non-Microsoft platforms, and MVVM is a pattern similar to Martin Fowler's Presentation Model (PM) pattern, as it has taken many of its concepts from PM.

It's all about the patterns

Both MVC and MVVM are patterns, meaning that they are solutions to recurring design problems in software development. Patterns can show interactions between objects in various ways, as the few listed below will demonstrate:

  • General interactions
    • Interaction through inheritance and OOP principles
  • UI interactions
    • Interaction between models, views, and controllers or models, views, and ViewModels
  • Data access patterns
    • ORM mappings, Active Record pattern, POCOs in DALS

Once you're aware of patterns, you can then apply them in software to make your code more stable, consistent, and maintainable. A variety of tools and frameworks exist that can easily help find the best pattern and/or implementation for your specific business problem/domain. In particular, the MVC and MVVM patterns are both UI interaction patterns with MVC being the web UI pattern and MVVM being a desktop UI pattern. You can implement either pattern in Visual Studio, and the ASP.NET MVC project template in particular guides developers to use the MVC pattern.

In addition to MVC & MVVM there are many patterns that are worth reading up on.

Comparing MVC and MVVM: the patterns.

Since MVC and MVVM are geared towards different application paradigms altogether, i.e., ASP.NET MVC for web and MVVM desktop, they need to behave in distinctly different ways, with the most noticeable distinction being the controller from MVC... 

image

...and the ViewModel from MVVM...

image

The controller in MVC accepts HTTP requests, fetches data from the model, and routes that model to the view for output. In a desktop app, there is no routing or URLs; but desktop apps still feature navigation, which is part of the UI and therefore needs to be part of a good UI pattern. ViewModels are the piece that accomplishes this task, as the ViewModel in MVVM takes the responsibility of performing, or exposing the command that house all the UI logic in addition to fetching the data and data binding.

Views must behave differently as web and desktop applications use very different ways to render information for user interaction. Additionally, applications over http are considered stateless, whereas desktop applications have full connectivity over a LAN and contain and transport lots of data easily. Views in MVC only display data and perform basic client side UI duties usually with JavaScript (form submission, validation, effects, etc...). On the other hand, View in MVVM have a rich databinding and validation framework, when combined with the business logic and navigation exposed by the ViewModel, lead to a very rich User Experience

Models behave the same way in either pattern - they're full of data (and sometimes logic). You may want to use other patterns at the model level for better code organization, maintenance, and a finer separation of concerns. The repository pattern with Entity Framework is a popular pattern, and Julie Lerman has a great explanation within series of posts on it.

Within both MVC and MVVM exists the ViewModel. Despite the same name, there are marked differences within how ViewModels in either pattern work. 

Comparing MVC & MVVM: the ViewModels.

There are ViewModels in MVC, but they have different responsibilities than an MVVM ViewModel.

  • An MVC ViewModel is two or more models combined (smashed together), or a customized subset of a model or models that provides all the information necessary to its corresponding view. It's basically a hybrid model, and the best part - the views don't know the difference.  
  • In MVVM, the ViewModel serves the same function as it does in MVC, but it also takes on the responsibility of a controller.

This is because although they're both user interface patterns, a web application and a desktop application behave very differently, with a few key reasons below:

  • Navigation
    • As previously mentioned, navigation is completely different in both type of apps, and SilverLight/WPF applications do not use routing or URLs.
  • Security
    • Desktop applications connecting to LAN resources can happily save data locally, with security restrictions, of course. One reason is because browser based applications have no access at all to resources on the user's machine, and rightfully so, or any web site could add what they'd like to the users machine (not acceptable!). Users specifically choose to install desktop apps. When the app runs under the "Standard Users" group[1], it enjoys a wider range of UI activities than a web application will.
  • Model/Data Binding
    • Because of the stateless environment of web apps vs. the stateful environment of desktop apps, binding happens in different ways. Controllers and/or models in MVC must parse and match HTTP form elements to model properties for model binding to occur. This happens for each HTTP request, keeping in mind that the web app has no knowledge of any previous requests, even by the same user agent (browser). On the other hand, while ViewModels in MVVM apps match up the model with the view via data binding, it has no need to deal with HTTP request cycles. Networked desktop apps have built-in capacity to know what's going on between requests for data from the database.
  • Validation
    • ViewModels in both MVC and MVVM both can perform validation; however MVC 3 validation with Razor exploits unobtrusive jQuery on the client side in tandem with data annotations on the server. Alternatively, MVVM depends on data binding properties. MVC 3 also offers remote validation for dealing with the stateless nature of the web, whereas MVVM on desktop apps have immediate access to data through data binding to validate.

As you can see, there's both similarities and differences between the patterns; mostly dependent on the environments - browser or OS.

Summary.

Since they're all in the same category, UI presentation patterns, you can use MVC on WPF, SilverLight or Winforms apps & MVVP in web applications. A note of caution: before running off swapping out patterns, be sure that what you're going to use will actually work the best for your project.

By now you may be wondering where MVP pattern for ASP.NET, Winforms or WPF/SL fits in. MVP, or Model-View-Presenter, is yet another UI pattern for web or desktop development. Experiment with other patterns such as MVP to see what helps your coding efforts the most.

Resources:

Phil Japikse writes, talks, and mentors on patterns and testing with MVVM, WPF, & SL. Phil was also kind enough to take some time to compare the finer points of the patterns with me before posting this.

WPF Apps With The Model-View-ViewModel Design Pattern.

Karl Shifflett's Blog. Karl is a Program Manager at Patterns & Practices at Microsoft.

[1] The "Standard Users" group contains users with very basic privileges in the Windows OS, but has more privilege than the anonymous web user (IUSR_XX or ASPNET).

23 Comments

  • Chris said

    Rachel,
    That's really a great comparison with some good detail.
    It might be worth mentioning that ASP.NET MVC is an implementation of the Model2 pattern, which adapts MVC from its normal desktop orientation for the web.

  • Steve said

    A few things. MVC is not just a web Pattern, many other languages on other platforms make use of it. Such as in native iPhone development. Silverlight runs mainly within a browser and is stateful due to running as a plugin on the clients machine and has navigation through HTTP requests but MVVM is still a recommended pattern in this environment - not just for desktop. Entity Framework isn't a pattern, its an implementation of an ORM.

    Otherwise, a good article.

  • Rachel said

    @Steve,

    For the context of this blog I am viewing MVC as a web pattern, and of course, it can be used elsewhere.

    Agreed, the MVVM pattern works great with SL in the browser as well, I did mean to mention that (forgot!).

    For EF/RP - the post says "The repository pattern with Entity Framework". Perhaps not the best grammatical sentence. To rephrase: I meant the repository pattern, and that it can be done in EF (without getting religious about the repo pattern).

  • Michael L Perry said

    Rachel,

    Thanks for taking on this question. It is frequently asked, but infrequently answered.

    I usually answer the question by drawing two similar diagrams, with just two differences. First, in MVC the View can see the Model directly, so I add a line between them (this is the distinction between MVC and MVP). Second, in MVVM I move the View and the Model on opposite sides of the View Model to make it clear that the View never sees the Model without the View Model being in between. So I draw the MVC triangle and the MVVM cake.

  • Bart Czernicki said

    The article could be really just a couple sentences...how the VM in MVVM is really the controller and that VMs in M-V-C are really M-VM-C.

    All your other stuff is MVC for the web. For example, saying that MVC handles HTTP requests in the controller...no on the iPhone. You are comparing the MVC and MVVM IMPLEMENTATIONS inside Silverlight/WPF vs ASp.NET MVC

  • Rachel said

    @Bart,

    Yes, that's exactly what I was comparing, hence the word "ASP.NET" in front of "MVC" and "SL/WPF" in front of MVVM throught the post.

    Also -
    "The elevator pitch: MVC is a web UI pattern, and ASP.NET MVC is Microsoft's implementation of it. MVVM is Microsoft's implementation of a desktop UI pattern in WinForms, SilverLight or WPF. "

  • Vishwanath said

    Thank you.. It is very nice article.

    I went through many articles, but finding variations in the explanitation. I am confused.

    Link 1 : http://nirajrules.wordpress.com/2009/07/18/mvc-vs-mvp-vs-mvvm/

    The input is directed at the "View" first, not the "Controller".

    Link 2 : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

    The input is directed at the Controller first, not the view.


    As you have explained in this article
    1. Model does not talk to View.


    I have posted this same question in the above mentioned link also, just curious to know the right answer.

    Thank you.

  • Rachel said

    @Vishwanath,

    In the first article, the author is starting with the view from the perspective of the end user, as the end user would fill in the HTML form then click submit. In this case the user is interacting with the view, on the client side. The form submission goes to the controller, which is the developer's perspective where D'Arcy (second article) and I used as a startig point.

    Either way is technically correct, it just depends on where in the cycle the author wants to start.

  • Ted Bissell said

    Rachel,
    The power of MVC 3.0 and further developments on my web get top presentation. Nice job so fah, so good! Please feel free to contribute as much as you'd like on my blog also...But can we see a real life example??!! I mean...this is stuff that you are showing is demo; right? or do you have presentations from original work at the Writer's Guild, Universal Studios, and Sony Pictures Entertainment to back up your work? Cheers, Ted

  • Rachel said

    Ted,

    This is a theory blog post, not a how to blog post, without code, discussing architecture. There are no samples real life or otherwise for this.

    For other blog posts: in trying to keep brevity in the content I've chosen to show the smallest amount of code possible. This also helps weed out unnecessary information that gets in the way of learning the point at hand.

  • Mark said

    The MVC pattern predates the web by a decade and a half. The MVC pattern was conceived by the Smalltalk project team at Xerox PARC in the late seventies.

  • Rachel said

    I mentioned that "MVC is an old pattern, in use for decades in non-Microsoft platforms, and MVVM is a pattern similar to Martin Fowler's Presentation Model (PM) pattern, as it has taken many of its concepts from PM.". I just didn't mention specifics. Thanks for the extra info, Mark.

  • Terry said

    Rachel,
    In the summary it says "& MVVP in web applications". Should that be MVVM?

    I THINK your information will be very helpful to us as we are trying to duplicate a pattern a vendor had shown us and are trying to determine if we would truly using MVVM in our Web applications, or if this was some odd hybrid, and if we were attempting to do something that might not be wise.

  • Rachel said

    Terry,

    Yes it should say MVVM. I never actually noticed that until now. LOOL! <-see what i did there? :)

    As long as the pattern brings you benefits by the facilitation of getting your business requirements done, code maintenance, performance, etc...then you don't absolutely have to stick to the pure versions of a pattern.

  • Giovanny said

    Hi Rachel, I dissent the next afirmation, "Views in MVC only display data and perform basic client side UI duties usually with JavaScript... On the other hand, View in MVVM have a rich databinding and validation framework,... , lead to a very rich User Experience"

    I don't know if you has tested with GWT for example, wich offers a very rich user interfaces, databinding, valitations, and so on, so, also there are so much javascript apis to build rich UI in web environment, We live in the world wile web 2.0, so I think the time of the deskop apps has finished.

  • Rachel said

    Giovanny,

    I'm talking about views specifically in ASP.NET MVC here, so that is the reasoning behind that statement. It is true that views in ASPNET MVC are there to only perform those duties. GWT has nothing to do with this example. Also, to be specific, JavaScript is not an ASPNET MVC view, it is the script inside the view.

  • John said

    This is another article discussing <a href="http://www.sharpgoals.com/dot-net-training-blog/post/2012/05/06/Using-MVVM-in-ASPNET-MVC.aspx">MVVM and ASP.NET MVC </a>

  • Tiago Freitas Leal said

    Nice post. You might like to know that at http://mvvmfx.codeplex.com/ you will find some useful MVVM stuff fow Windows Forms:
    1) a databinding library with converters that can also bind an Action to a property change
    2) a command binding library that can bind an Action to any input event of any UI component

Comments have been disabled for this content.