Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Visual C# » Model View Presenter (MVP) design pattern and data binding

Model View Presenter (MVP) design pattern and data binding

Model View Presenter (MVP) design pattern is the evolution of the MVC design pattern and it’s aimed at providing a cleaner separation of concerns between the view, the model, and the controller improving the architecture (you can use several UI technologies without recompiling the business logic components) and testability of the enterprise solution. The pattern was originally developed at Taligent in the 1990s. In this article, I will explain the principles and how to use the MVP design pattern along with data binding with an example using C# language in Microsoft.NET.

Author Rank :
Page Views : 44086
Downloads : 0
Rating :
 Rate it
Level : Advanced
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Introduction

Model View Presenter (MVP) design pattern is the evolution of the MVC design pattern and it's aimed at providing a cleaner separation of concerns between the view, the model, and the controller improving the architecture (you can use several UI technologies without recompiling the business logic components) and testability of the enterprise solution. The pattern was originally developed at Taligent in the 1990s.

In this article, I will explain the principles and how to use the MVP design pattern along with data binding with an example using C# language in Microsoft.NET.

The Model View Presenter (MVP) design pattern

Starting from the Model View Controller (MVC) design pattern, creators of MVP neatly separated the model from the view/controller pair. The core of MVP is the strictly regulated interaction taking place between the view and the controller. In MVP, this controller is renamed to presenter.
In the Figure 1, you can see an overview of the MVP design pattern.

image1.gif

Figure 1

As you can see in the Figure 1, the view and model are neatly separated (they don't know each other) and the view exposes an interface for the communication of the presenter with the view and in this way the presenter doesn't know the underlying UI technology and the view is mockable for testing purposes. As well as the presenter knows the model and can invoke its operations.

Note that each Presenter object has exactly one reference to a View object, and each View object has exactly one reference to a Presenter object. There is one Model object for the whole application. As you can see it's required to define an interface and a presenter for every View object of your application (each Web form in ASP.NET and form in Windows).

Let's explain the MVP triad at a glance.

The Model represents the business objects of the domain problem. That is business entities encapsulating the data, business services implementing the business logic and rules of your solution. It's a domain object and should have no knowledge of the user interface, unlike previous design patterns such as MVC (Model-View-Controller) where the model implements the user interface to manipulate it which is a big design error if you try to separate the concerns of the domain.

The View is responsible to display the content of the model and interact with the user's events regarding the UI technology of the solution.
The Presenter is responsible to interpret the user's events and the communication with the model objects. It implements the main workflow of the application. This is where the heart of the application lies.

It's remarkable to say that Martin Fowler has extended the original MVP design pattern with Passive View and Supervising Controller/Presenter.
In the case of the Passive View pattern, the main idea is to have no dependencies between the View and the Model concerns and the view is dumb. The Supervising Controller is a flexible interpretation of the original MVP design pattern and the view is not completely dumb and has some responsibilities.

Now well, my approach, to architect an enterprise-class application for being implemented using Microsoft technologies, is to separate concerns in multiple layers and follow the MVP design patter along with data binding (data binding using BindingSource support in Windows applications and data binding with ObjectDataSource support in ASP.NET applications). The View has some responsibilities such as displaying, formatting and gathering data as well as handling user interaction's events. The Presenter has the responsibility to interpret the messages sent and received from the View as well as to invoke the underlying business objects in the business logic layer in the Model. Now, the communication between the layers of the application is through Data Transfer Objects (DTO). The use of DTO is trade-off because we create new DTO, we're increasing the cost of the complexity of the solution and this cost is justified in large enterprise applications. For small and medium application, it makes sense to reference the business objects directly from the View concern (and bind the data represented by the business object in the controls) in order to avoid the definition of new DTO. The idea is to use the data model represented by the business object as the DTO. But it's not correct to invoke operations and business logic directly from the View (data access methods, calculation, invocation of external services, etc).

The solution, which I will explain in this article, will be based on the MVP design pattern along with data binding for small enterprise application.

Implementing the Model View Presenter (MVP) design pattern

Now let's go and implement the principles and concepts of the Model View Presenter (MVP) design pattern along with data binding in a multi-layer enterprise application using C# in Microsoft.NET.

Let's open the Visual Studio.NET 2008 IDE and create an example solution (see Figure 2).

image2.gif

Figure 2

For this example, we're going to create an application which enables managing the contacts of one enterprise. The data source is the Person.Contact table in the AdventureWorks database shipped with SQL Server 2005.
Let's add the business logic layer using a Class Library project (see Figure 3).

image3.gif

Figure 3

Next step is to add the business entities and objects which model your problem domain (see Listing 1). For the definition of the business entities we're going to use strongly typed Data Set and for the data access code we're going to rely on the underlying table adapters.

Let's add a DataSet to the project named DSContactManager as shown in the Figure 4.

image4.gif

Figure 4

Let's add a Contact data table and its underlying table adapter (see Figure 5).

image5.gif

Figure 5

Now let's add the business service objects to implement the business logic concerning the Contact business entity (see Figure 6).

image6.gif

Figure 6

The code definition for the business services regarding the contact entity is the Listing 1.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusinessLogicPkg
{
    public class ContactBizServices
    {
        private DSContactManager m_dsContact;

        public ContactBizServices(DSContactManager dsContact)
        {
            this.m_dsContact = dsContact;
        }

        public void Load()
        {
            DSContactManagerTableAdapters.ContactTableAdapter taContact = new BusinessLogicPkg.DSContactManagerTableAdapters.ContactTableAdapter();
            taContact.Fill(this.m_dsContact.Contact);
        }

        public void Save()
        {
            DSContactManagerTableAdapters.ContactTableAdapter taContact = new BusinessLogicPkg.DSContactManagerTableAdapters.ContactTableAdapter();
            taContact.Update(this.m_dsContact.Contact);
        }
    }
}

Listing 1

Now let's add the Presentation layer where the presenter objects lies using a Class Library project (see Figure 7).

image7.gif

Figure 7

We need to add a reference to the business logic layer in the PresentationLayer as in the Figure 8.

image8.gif

Figure 8

Next step is to add the ContactManagerPresenter class to handle the workflow for the communication between the UI controls and the model objects as well as to add the IContactManagerView interface to define the interface to be implemented by the underlying UI artifacts which need to communicate with the Presenter artifact.

In order to define the IContactManagerView interface, we deal with the user stories and requirements and in this case, we want to load contact data, to be changed and then save the changes. We need to access to the data model (the strongly typed Data Set DSContactManager) as the DTO and send a message to the user notifying the status of the performed operation (see Listing 2).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLogicPkg;

namespace PresentationLayerPkg
{
    public interface IContactManagerView
    {
        DSContactManager ContactManager { get; }
        void SendMessageInfo(string strMessage);
    }
}

Listing 2

Now let's define the workflow of the presenter object as shown in Listing 3.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessLogicPkg;

namespace PresentationLayerPkg
{
    public class ContactManagerPresenter
    {
        private IContactManagerView m_objContactManagerView = null;

        public ContactManagerPresenter(IContactManagerView objContactManagerView)
        {
            this.m_objContactManagerView = objContactManagerView;
        }

        public void LoadContact()
        {
            ContactBizServices objContactBizServices = new ContactBizServices(this.m_objContactManagerView.ContactManager);
            objContactBizServices.Load();
            this.m_objContactManagerView.SendMessageInfo("Operation has successfully ended");
        }

        public void SaveContact()
        {
            ContactBizServices objContactBizServices = new ContactBizServices(this.m_objContactManagerView.ContactManager);
            objContactBizServices.Save();
            this.m_objContactManagerView.SendMessageInfo("Operation has successfully ended");
        }

    }
}

Listing 3

Now let's go to the Windows Forms project to define the user interface and communication with the Presenter artifact.

Fist step is to add a reference to the PresentationLayerPkg library as shown in Figure 9.

image9.gif

Figure 9

We need to a reference to the BusinessLogicPkg library as well because we're going to use the data model as our Data Transfer Object (DTO) (see Figure 10).

image10.gif

Figure 10

Now let's add a data source object. Open the Data Sources window and click on the Add New Data Source link to open the Data Source Configuration Wizard. Then select the DSContactManager object in the BusinessLogicPkg library (see Figure 11).

image11.gif

Figure 11

Then drag and drop the defined data source onto the form as a grid control. This action adds a DataGrid control and a binding navigator control in the form. Delete the save icon on the binding navigator to do the load and save actions manually.

Next step is to drag and drop two buttons on the form (one to load the data and the other to save the date after changes) and the underlying event handlers.

Next step is to implement the view interface defined in the presenter library. We need to return an instance of the DSContactManager and show an information message (see Listing 4).

#region IContactManagerView Members

        public BusinessLogicPkg.DSContactManager ContactManager
        {
            get
            {
                return this.dSContactManager;
            }
        }

        public void SendMessageInfo(string strMessage)
        {
            System.Windows.Forms.MessageBox.Show(strMessage, "Information Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

Listing 4

And the implementation of the event handlers is done by invoking the underlying methods in the presenter artifact (see Listing 5).

private void btnLoad_Click(object sender, EventArgs e)
        {
            ContactManagerPresenter objContactManagerPresenter = new ContactManagerPresenter(this);
            objContactManagerPresenter.LoadContact();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            ContactManagerPresenter objContactManagerPresenter = new ContactManagerPresenter(this);
            objContactManagerPresenter.SaveContact();
        }

Listing 5

The complete code for the Windows forms is shown in the Listing 6.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PresentationLayerPkg;

namespace WinMVPDatabinding
{
    public partial class Form1 : Form, IContactManagerView
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            ContactManagerPresenter objContactManagerPresenter = new ContactManagerPresenter(this);
            objContactManagerPresenter.LoadContact();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            ContactManagerPresenter objContactManagerPresenter = new ContactManagerPresenter(this);
            objContactManagerPresenter.SaveContact();
        }

        #region IContactManagerView Members

        public BusinessLogicPkg.DSContactManager ContactManager
        {
            get
            {
                return this.dSContactManager;
            }
        }

        public void SendMessageInfo(string strMessage)
        {
            System.Windows.Forms.MessageBox.Show(strMessage, "Information Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion
    }
}


Listing 6

The Figure 12 shows when you run the application.

image12.gif

Figure 12

Conclusion

In this article, I've explained the concepts of the Model View Presenter (MVP) design pattern along with data binding through an example.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by sudarshan mishra on Jun 02, 2011
Contents added by prashanth bathala on Jun 26, 2009
I can understand  theme of mvp, but i can't understand pratically how to implement the mvp.
 [Top] Rate this article
 
 About the author
 
John Charles Olamendy
He’s a senior Integration Solutions Architect and Consultant. His primary area of involvement is in Object-Oriented Analysis and Design, Database design , Enterprise Application Integration, Unified Modeling Language, Design Patterns and Software Development Process. He has knowledge and extensive experience in the development of Enterprise Applications using Microsoft.NET and J2EE technologies and standards. He is proficient with distributed systems programming; and business-process integration and messaging using the principles of the Services Oriented Architecture (SOA) and related technologies such as Microsoft BizTalk Server, Web Services (Windows Communication Foundation, WSE, BEA WebLogic, Oracle AS and Axis) through multiple implementations of loosely-coupled system. He’s a prolific blogger contributing to .NET and J2EE communities and actively writes articles on subjects relating to integration of applications, business intelligence, and enterprise applications development. He holds a Master’s degree in Business Informatics at Otto Von Guericke University, Magdeburg, Germany. He was recently awarded as MVP. He currently works in the telecommunication industry and delivers integration solutions for this industry. He harbors a true passion for the technology.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
More than one view by Mads On September 10, 2009
First of all, I like this MVP implementation due to its simplicity. However, I have a question regarding multiple views.

Let's say we want to add a ContactDetailView (and therefore also a ContactDetailPresenter) which should be shown when double-clicking a contact in the grid. Whos responsibility is it to show the ContactDetailView and how should we pass parameters to the view?

I would think that the ContactManagerView would handle the double-click event, then calling a method in the ContactManagerPresenter. This method would then call an interface-defined method in the ContactManagerView, which would then show the ContactDetailView.

I'm not sure if that's the right way to do it and also what about passing a contact id or contact entity to the ContactDetailView so that it can populate its controls with contact data?
Reply | Email | Modify 
Dataset variable by Kenny On September 19, 2009
Hi,

First of all , nice article. but I have a small question...
When you create the datasource on your view (form) then you add the property on your form that returns the instance of the dataset variable to the presenter.

When I create a datasource and point to the DSContactManager object, visual studio creates the datasource and a bindingsource , ... but I do not have a variable for the dscutomer dataset. I only see the property in my intellisense but not a variable of the dataset...

any ideas???

thx
Reply | Email | Modify 
Re: Dataset variable by Kenny On September 19, 2009
I found what was wrong and turned out that I did not read the article well enough ;-)

I created a datasource while setting the properties of the datagrid but I needed to create the datasource in the datasource window and then draag the table onto the form to create the grid.

That way VS also creates a dataset

greets
Reply | Email | Modify 
Doesn't adding a reference to the BusinessLogicPkg library in the view violate MVP? by J On March 15, 2010
Doesn't adding a reference to the BusinessLogicPkg library in the view violate MVP?

 

Reply | Email | Modify 
Source Code by j On August 5, 2010
Where can I download the
source code?
Reply | Email | Modify 
Is it realy so? by Gary On August 30, 2010
"It's a domain object and should have no knowledge of the user interface, unlike previous design patterns such as MVC (Model-View-Controller) where the model implements the user interface to manipulate it which is a big design error if you try to separate the concerns of the domain." I don't agree with you in that case. Model do not know about view but it is Observable/Notifier in MVC. But of course there is a assosiation between view and model view to model in MVC what is perhaps not good.
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.