TopMenu

Simplest example of MVP design pattern in Asp.net


These days design patterns such as MVC and MVP in ASP.Net are being used in Enterprises. When I heard of these terms I searched Google and read books but I was always confused because the examples given were quite complex. Then recently I worked on a project of MVP and then I understood all the insides in it and decided to write a small and simple article for understanding MVP. So here we'll discuss the MVP pattern. The MVP is Model, View , Presenter. This pattern is how the interaction between these layers can be done.

View: View can be your Aspx page in your web applications or any user controls/Interface for the end user.
Model: Contains all the business logic.

Presenter: Works as the intermediate agent for Model and View. It binds the view with the model. See the diagram below.

MVP1.gif

In the following diagram a couple of blocks are added which are interfaces through which the presenter will interact.

MVP2.gif

Let's take a simple example of how to implement it.

Create a web application project in your Visual Studio. Now add 3 more classes named View.cs, Presenter.cs and Model.cs and add the interfaces IView and IModel.

MVP3.gif

Start with the aspx page (View). Add a label, a button and a TextBox.
<html xmlns="http://www.w3.org/1999/xhtml" >
<
head runat="server">    <title>Untitled Page</title>
</
head>
<
body>    <form id="form1" runat="server">    <div>        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> &nbsp;    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    </div>    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />    </form>
</
body>
</
html>

Now we won't write anything in aspx.cs file. First write the code in IView.
namespace WebApplication1
{
   
public interface IView    {
       
String Label { get; set; }
       
String TextBox { get; set; }
    }
}

Similarly write some code in IModel.cs
namespace WebApplication1
{
   
public interface IModel    {
      
List<String> setInfo();
    }
}
Now Model.cs. Let's say we send the information about the Label and TextBox from Model.
namespace WebApplication1
{
   
class Model : IModel    {
       
public List<String> setInfo()
        {
           
List<String> l = new List<string>();
            l.Add(
"Enter Name:");
            l.Add(
"Use capital letter only");
           
return l;
        }
    }
}
Now we need to write some code in the presenter so that the View and Model can communicate with each other. It'll go like this:
namespace WebApplication1
{
   
public class Presenter    {
       
IView _pView;
       
IModel _pModel;
       
public Presenter(IView PView, IModel PModel)
        {
            _pView = PView;
            _pModel = PModel;\
        }
       
public void BindModalView()
        {
            
List<String> ls = _pModel.setInfo();
            _pView.Label = ls[0];
            _pView.TextBox = ls[1];
        }
    }
}


Finally go to aspx.cs and Implement the IView.
public partial class _Default : System.Web.UI.Page, IView    {
       
protected void Page_Load(object sender, EventArgs e)
        {
        }
        #region IView Members
        public string Label
        {
           
get            {
               
return Label1.Text;
            }
           
set            {
                Label1.Text =
value;
            }
        }
        public string TextBox
        {
           
get            {
               
return TextBox1.Text;
            }
           
set            {
                TextBox1.Text =
value;
            }
        }
        #endregion
Add an event for the button and write the code to get the data from Model through presenter and then bind it to the View. In the constructor of Presenter we passed "this" which means reference of the same aspx page.
protected void Button1_Click(object sender, EventArgs e)
{
      
Presenter p = new Presenter(this, new WebApplication1.Model());
      p.BindModalView();
}

And you have implemented a small application with MVP pattern. Now I want to add a few more lines to show the advantage of adding IView and IModel interface. Using these interface your code will be more manageable and reusable. Moreover if you want to test your application you can create a TestProject and can use the IView and IModel for Mock Implementation. And unit test your application.

In the next part of this article I'll try to show you how to test this application using NUnit or any other tool like MockUp for Unit testing.

Hope this was helpful.

3 comments:

  1. This is really very simple and shortest example to understand MVP

    ReplyDelete
  2. Nice and usefull post for beginners in patterns.

    ReplyDelete
  3. hi,

    I am able to see 2 ways in which View and Presenter can exist.
    in your example you have a "Presenter has a View" approach.
    in this http://www.martinhunter.co.nz/articles/MVPC.pdf, they use the opposite, where "View has a Presenter" approach.

    I am building some service which we plan to use via multiple and different views. So Presenter and View need to be able to run on separate machines. Views can vary from simple CommandLine, WebPage, to RichDesktopApps (imagine Adobe Air).
    So I am planning for a "Presenter,Model" on the server side and View on the client side.
    So I am finding "View contains a Presenter" approach as the only feasible one.

    any comments?

    ReplyDelete