Click here to Skip to main content
Click here to Skip to main content

Understanding Basics of UI Design Pattern MVC, MVP and MVVM

By , 20 Jul 2011
 

Introduction

This is my first article and I hope you will like it. After reading this article, you will have a good understanding about "Why we need UI design pattern for our application?" and "What are basic differences between different UI patterns (MVC, MVP, MVVP)?”.

In traditional UI development - developer used to create a View using window or usercontrol or page and then write all logical code (Event handling, initialization and data model, etc.) in code behind and hence they were basically making code as a part of view definition class itself. This approach increased the size of my view class and created a very strong dependency between my UI and data binding logic and business operations. In this situation, no two developers can work simultaneously on the same view and also one developer's changes might break the other code. So everything is in one place is always a bad idea for maintainability, extendibility and testability prospective. So if you look at the big picture, you can feel that all these problems exist because there is a very tight coupling between the following items.

  1. View (UI)
  2. Model (Data displayed in UI)
  3. Glue code (Event handling, binding, business logic)

Definition of Glue code is different in each pattern. Although view and model is used with the same definition in all patterns.

In case of MVC it is controller. In case of MVP it is presenter. In case of MVVM it is view model.

If you look at the first two characters in all the above patterns, it remain same i.e. stands for model and view. All these patterns are different but have a common objective that is “Separation of Duties"

In order to understand the entire article, I request readers to first understand the above entity. A fair idea about these will help you to understand this article. If you ever worked on UI module, you can easily relate these entities with your application.

MVC (model view controller), MVP (model view presenter) and MVVM (model view view model) patterns allow us to develop applications with loss coupling and separation of concern which in turn improve testability, maintainability and extendibility with minimum effort.

MVVM pattern is a one of the best solutions to handle such problems for WPF and Silverlight application. During this article, I will compare MVC, MVP and MVVM at the definition level.

MVP & MVC

Before we dig into MVVM, let’s start with some history: There were already many popular design patterns available to make UI development easy and fast. For example, MVP (model view presenter) pattern is one of the very popular patterns among other design patterns available in the market. MVP is a variation of MVC pattern which is being used for so many decades. Simple definition of MVP is that it contains three components: Model, View and presenter. So view is nothing but a UI which displays on the screen for user, the data it displays is the model, and the Presenter hooks the two together (View and model).

View,Model,Presenter,Model

The view relies on a Presenter to populate it with model data, react to user input, and provide input validation. For example, if user clicks on save button, corresponding handling is not in code behind, it’s now in presenter. If you wanted to study it in detail, here is the MSDN link.

In the MVC, the Controller is responsible for determining which View is displayed in response to any action including when the application loads. This differs from MVP where actions route through the View to the Presenter. In MVC, every action in the View basically calls to a Controller along with an action. In web application, each action is a call to a URL and for each such call there is a controller available in the application who respond to such call. Once that Controller has completed its processing, it will return the correct View.

In case of MVP, view binds to the Model directly through data binding. In this case, it's the Presenter's job to pass off the Model to the View so that it can bind to it. The Presenter will also contain logic for gestures like pressing a button, navigation. It means while implementing this pattern, we have to write some code in code behind of view in order delegate (register) to the presenter. However, in case of MVC, a view does not directly bind to the Model. The view simply renders, and is completely stateless. In implementations of MVC, the View usually will not have any logic in the code behind. Since controller itself returns view while responding to URL action, there is no need to write any code in view code behind file.

MVC Steps

Step 1: Incoming request directed to Controller.

View,Model,Presenter,Model

Step 2: Controller processes request and forms a data Model.

View,Model,Presenter,Model

Step 3: Model is passed to View.

View,Model,Presenter,Model

Step 4: View transforms Model into appropriate output format.

View,Model,Presenter,Model

Step 5: Response is rendered.

View,Model,Presenter,Model

So now you have basic understanding of MVC and MVP. Let’s move to MVVM.

MVVM (Model View ViewModel)

The MVVM pattern includes three key parts:

  1. Model (Business rule, data access, model classes)
  2. View (User interface (XAML))
  3. ViewModel (Agent or middle man between view and model)

View,Model,ViewModel

Model and View work just like MVC and “ViewModel” is the model of the View.

  • ViewModel acts as an interface between model and View.
  • ViewModel provides data binding between View and model data.
  • ViewModel handles all UI actions by using command.

In MVVM, ViewModel does not need a reference to a view. The view binds its control value to properties on a ViewModel, which, in turn, exposes data contained in model objects. In simple words, TextBox text property is bound with name property in ViewModel.

In View:

<TextBlock Text="{Binding Name}"/> 

In ViewModel:

public string Name
        {
            get
            {
                return this.name;
            }
            set
            {
                this.name = value;
                this.OnPropertyChanged("Name");
            }
        }

ViewModel reference is set to a DataContext of View in order to set view data binding (glue between view and ViewModel model).

Code behind code of View:

public IViewModel Model
        {
            get
            {
                return this.DataContext as IViewModel;
            }
            set
            {
                this.DataContext = value;
            }
        }

If property values in the ViewModel change, those new values automatically propagate to the view via data binding and via notification. When the user performs some action in the view for example clicking on save button, a command on the ViewModel executes to perform the requested action. In this process, it’s the ViewModel which modifies model data, View never modifies it. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model doesn’t have any idea about ViewModel and view exists.

Where to Use What in the .NET World

  • Model-View-Controller (MVC) pattern
    • ASP.NET MVC 4 Link
    • Disconnected Web Based Applications
  • Model-View-Presenter (MVP) pattern
    • Web Forms/SharePoint, Windows Forms
  • Model-View-ViewModel (MVVM) pattern
    • Silverlight, WPF Link
    • Data binding

Sources and References

History

  • 18th July, 2011: Initial version
  • 19th July, 2011: Modified content in MVVM section

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Avtar Singh Sohi
Web Developer
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberBiswojit Kumar Sahu24 Apr '13 - 1:47 
Could not able to understand the difference. Please provide the difference in a very short and crispy way.
QuestionThanks! Great article!memberalexrinconz8 Apr '13 - 6:07 
I have been looking for some easy explanation for this pattern, this really helped me!
GeneralMy vote of 5memberNani Babu9 Dec '12 - 23:03 
Nice article
QuestionNice article...memberabhijeet.gaikwad18@gmail.com10 Oct '12 - 6:57 
Wink | ;) Helpful article
QuestionNice article...memberabhijeet.gaikwad18@gmail.com10 Oct '12 - 6:57 
Helpful article
QuestionGreat article. Thx.memberSharpGoals6 May '12 - 7:51 
MVVM and ASP.NET MVC
GeneralMy vote of 4memberhariazeez20 Dec '11 - 19:15 
nice article for beginners..
QuestionGreat...memberkasunt26 Oct '11 - 6:23 
Incredible posting! I truly enjoyed reading it, you could be a great author.I will be sure to bookmark your blog and will come back at some point
 

http://ktwis.blogspot.com/[^]
GeneralMy vote of 5memberimpeham26 Oct '11 - 1:17 
Very nice - thanks.
GeneralMy vote of 3memberSoren.Persian20 Aug '11 - 18:19 
not deep.
BugGood article, a relatively minor problemmemberfejustin17 Aug '11 - 20:42 
Good article, a relatively minor problem
"(MVC, MVP, MVVP)" is (MVC, MVP, MVVM)?
Questionnot badmemberCIDev8 Aug '11 - 3:32 
Clearly written and makes good use of illustrations, but I would like to see a more in depth coverage.
Just because the code works, it doesn't mean that it is good code.

GeneralMy vote of 5memberdxlee28 Jul '11 - 2:23 
Your article contains useful information. Thanks for sharing!
GeneralMy vote of 2memberGerman150326 Jul '11 - 22:19 
Only nice pictures!
GeneralMy vote of 5memberL Hills26 Jul '11 - 1:08 
Very nicely explained
GeneralMy vote of 2memberKarstenK25 Jul '11 - 22:37 
some colored graphics but not much more
QuestionVery Nice Short StorymemberKhaniya22 Jul '11 - 18:26 
I Have bookmarked..
Life's Like a mirror. Smile at it & it smiles back at you.- P Pilgrim
So Smile Please

AnswerRe: Very Nice Short StorymemberAvtar Singh Sohi25 Jul '11 - 7:44 
Thanks Khaniya.
QuestionAbout MVVM exampleprotectorPete O'Hanlon19 Jul '11 - 8:05 
Why have you set the VM in the code behind? I'm just curious because it's much more common to do this in the XAML. You can easily set this in the DataContext resource, e.g.
<Window.DataContext>
  <local:MyViewModel />
</Window.DataContext>
Also:
•ViewModel extends the model with behaviors the view could use.
No it doesn't. The VM should not extend the model at all.
 
•ViewModel provides data binding between View and Control.
Are you sure about this statement? The VM provides values that are suitable for binding.
 
•ViewModel passes Command between the view and Model.
No it doesn't. There is no interaction between the view and the model. The VM handles the Command and then takes an appropiate action based on the requirements of the command.

Forgive your enemies - it messes with their heads

My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility


AnswerRe: About MVVM examplememberAvtarSohi19 Jul '11 - 9:34 
Since You have to link the View with ViewModel anyway and I don't find any issue in using code behind. Please have a look this thread regarding setting datacontext
http://social.msdn.microsoft.com/Forums/en/wpf/thread/938c4454-ea64-40bb-a853-b56e1d099c90[^]
 
So its totally depend on the situation and you can use both approach.
 
ViewModel extend the model with behaviors the view Could use.
 
Here I am trying to say that View can not simply use Model directly, ViewModel helping View by extending model behavior to get what it want. Although if you look at this link it might help you to clear your understanding
 
http://stackoverflow.com/questions/977652/mvvm-inheritance-with-view-models[^]
 
ViewModel Provide data Binding between view and Control.
 
You are correct, Its my mistake. It was "data" not "control" I will update it soon. Thanks for pointing out.
 
ViewModel passes Command between the view and Model.
 
You are right. It doesn't pass command between view and model. Here what i try to say is that It revived command and then take action on model (Simply create connection between View and Model by taking appropriate action mentioned in command.
 
I will modify my article to remove these ambiguity.
 
Thanks for pointing out these point Smile | :)
GeneralRe: About MVVM exampleprotectorPete O'Hanlon19 Jul '11 - 9:42 
AvtarSohi wrote:
Here I am trying to say that View can not simply use Model directly, ViewModel
helping View by extending model behavior to get what it want. Although if you
look at this link it might help you to clear your understanding

I'm intimately familiar with the behaviours of Views and View Models, so I think my understanding is fine. I picked up the wording simply because extending means a particular term in Object Orientation, so it's important to ensure that what you are saying is unambiguous. Rather than use extend, you could use a term like acting as an intermediary.
 
Once you have amended your article, I'll be happy to vote.

Forgive your enemies - it messes with their heads

My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility


GeneralRe: About MVVM examplememberAvtar Singh Sohi20 Jul '11 - 1:40 
Please have a look Smile | :) Smile | :)
GeneralRe: About MVVM exampleprotectorPete O'Hanlon20 Jul '11 - 2:08 
Much better. Have my 5.

Forgive your enemies - it messes with their heads

My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility


GeneralRe: About MVVM examplememberMycroft Holmes24 Jul '11 - 20:09 
Pete O'Hanlon wrote:
Although if you

look at this link it might help you to clear your understanding

[snigger] [snigger]
Never underestimate the power of human stupidity
RAH

AnswerRe: About MVVM examplemvpNishant Sivakumar19 Jul '11 - 10:12 
Pete O'Hanlon wrote:
ViewModel extends the model with behaviors the view could use.
No it doesn't.
The VM should not extend the model at all.

In my opinion, it can under certain circumstances. Although I wouldn't call it "extending" the model.
 
Imagine a Model object called Person with FirstName and LastName properties. Now it's conceivable that a VM can expose a FullName property that returns FirstName + LastName.
Regards,
Nish
Are you addicted to CP? If so, check this out:
The Code Project Forum Analyzer : Find out how much of a life you don't have!
 
My technology blog: voidnish.wordpress.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 20 Jul 2011
Article Copyright 2011 by Avtar Singh Sohi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid