ASP.NET Model View Presenter


By pw zeus
Printer Friendly Version
View My Articles

  

This article is about Model View Presenter pattern. It is a very basic level article. I have read many articles on this but none of them were simple enough, at least for me.



Model View Presenter (It cannot get simpler then this)

Model – This is be your business object / service / data or a module which has logic in it

View – This is your UI which has controls / images / text etc.

Presenter – This is an object whose only task to join View and Model.

I will try to make is as simple as I can. We will be using C# with ASP.NET and Interfaces, so if you are not familiar with interfaces then look here. C# Interface

Objective:

Create a web page which will have one textbox, one button and one label.  User can enter text in the textbox and click on the button. It should display entered text in the label. For sake of logic we will append entered text with word “Hello” i.e. if user enters World and click on the button then label will display “Hello world”.

Model

Model is our logic layer; we will also create Interface which will represent model class.

 

Here is the I Model interface code:

public interface IModel

{

    string buildText(string text);

}

Here is the Model class code:

public class Model : IModel

{

          public Model()

          {

                   //

                   // TODO: Add constructor logic here

                   //

          }

 

    public string buildText(string text)

    {

        return string.Concat("Hello ", text);      

    }

 

}

 

View

Now let’s create UI. Just place label, textbox and button on the page. Do not write anything in code behind yet. We will also create Interface which will represent our UI.

Code for View:

<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="lbl" runat="server"></asp:Label>

        <asp:TextBox ID="txt" runat="server"></asp:TextBox>

        <asp:Button ID="bt" runat="server" Text="Enter" OnClick="btn_Click" />

    </div>

    </form>

</body>

</html>

Code for I View:

public interface IView

{

    string Lable

    {

        get;

        set;

    }

 

    string Text

    {

        get;

        set;

    }

   

}

 

 

Presenter

 

 

          Now let’s create presenter class, this is nothing but a c# file which will talk to both side of interfaces and pass message and data back and forth.

For sake of simplicity I will only make presenter talk to I view. The aim is to look at how presenter does not know anything about UI at all and still can be communication between model and view.

public class Presenter

{

    IView pview;

 

    public Presenter(IView view)

          {

        // Define prviate view interface as passed View

        pview = view; 

          }

 

    public string buildtext()

    {

        // Private view lable gets string back from Model object (Business object)

        Model m = new Model();

        pview.Lable = m.buildText(pview.Text.ToString());

        return pview.Lable.ToString();

    }

 

}

Lets look at this code, preety simple eh. Now we are missing something here right, how actually we will pass View to presenter and Where did our fevorite codebehind go ? Well here we will need code behind.

Code behind file for View.aspx.cs:

public partial class View : System.Web.UI.Page, IView

{

    // Declare IView Text property for Textbox

    public string Text

    {

        get { return txt.Text; }

        set { txt.Text = value; }

    }

 

    // Declare IView Lable property for Lable

    public string Lable

    {

        get { return lbl.Text; }

        set { lbl.Text = value; }

    }

   

   

    protected void Page_Load(object sender, EventArgs e)

    {

        // Send this object to presenter

 

    }

 

    protected void btn_Click(object sender, EventArgs e)

    {

        Presenter presenter = new Presenter(this);

        presenter.buildtext();

    }

}

Now lets look at this carefully, Our codebehind file is inheriting IView interface so it know what to implement.

So As you can see in code behind, we have declared two properties for Text and Label. That is our interface implimnation. Now lets look at what happens when user enters text and click the button. As you can see we are instantiating presenter class and sending “This” page object.

        Presenter presenter = new Presenter(this);

 

So then in our presenter class we have declare private IView interface and at the same time we are recieveing “This” object as Iview interface which came from button click.

In param constructor we will assign our received Iview to private view.

 

    IView pview;

 

    public Presenter(IView view)

          {

        // Define prviate view interface as passed View

        pview = view; 

          }

 

So now our pview contains copy of view. Now in code behind we will call build text method.

 

        presenter.buildtext();

 

If we look at the declaratoin, you can see that we are now creating new modle object and assign pview.lalbe to buidtext method. This method resides in model object and it appends “Hello” and returns string.

    public string buildtext()

    {

        // Private view lable gets string back from Model object (Business object)

        Model m = new Model();

        pview.Lable = m.buildText(pview.Text.ToString());

        return pview.Lable.ToString();

    }

Now remember as our view is reference based, pviewllable value is also going to affect view.lable property. So that means in our code behind lable.text propery is now set with new string.

That is it, you just implimented MVP pattern. Lets go thorugh It one again briefly.

1.    Develop Model object which will contain logic. Develop Imodel that represent model object.

2.    Develop UI View and Interface IView that represent UI.

3.    Develop Presenter which can communicate with both View and Model.

4.    Presenter may only have knowledge of interfaces.

5.    From code behind pass Iview to interface.

6.    From Presenter call Model object. [For simplycity I am not sugin IModel here]

7.    When button_click then pass text from textbox to presenter and pass it to model object.

8.    Get back string from modle and send it back to View.

 

 

 

NOTE :

This may not be the best solution for your scenario. My aim was to provide simplest example to implement MVP pattern. Please leave comment if you this this helps you or if this is complete BS :P.


Other must read links:

http://msdn.microsoft.com/msdnmag/issues/06/08/DesignPatterns/default.aspx
http://www.codeproject.com/useritems/ModelViewPresenter.asp
http://www.madprops.org/cs/blogs/mabster/archive/2006/08/21/5949.aspx 




button
 
Article Discussion: Model view presenter - It can not get simple then this
pw zeus posted at 07-Apr-07 08:00
Original Article

 
MVP frameworks
Oleg Zhukov replied to pw zeus at 24-Apr-08 05:15
Very nice and clear explanation! Even easier things are done with Model View Presenter framework such as MVC#.

promotion
Silverlight    WPF    WCF    WWF    LINQ   
JavaScript    AJAX    ASP.NET    XAML   
C#    VB.NET    VB 6.0    GDI+    IIS    XML   
.NET Generics    Anonymous Methods    Delegate   
Visual Studio .NET    Expression Blend    Virus   
Windows Vista    Windows XP    Windows Update   
Windows 2003 Server    Windows 2008 Server   
SQL Server    Microsoft Excel    Microsoft Word   
SharePoint    BizTalk    Virtual Earth   
.NET Compact Framework    Web Service   

"Everything" RSS / ATOM Feed Parser
How to send and receive messages through message queuing in .Net
How to Read text file as database
SQL Server 2005 Paging Performance Tip
Display code of web page.
Fully Scalable Excel File Importer class for .net using Microsoft Jet driver
Generic Chart Color Manager class that can be used for any charts
Helper class to style the infragistics wingrid
Using Reflection to detemine as Assembly Info in and out.
Helper class to play with Window (Owners and position)
Resolving displayname from the culture using the XmlLanguage and LanguageSpecificStringDictionary class
Manipulate file attributes in VB.NET
Forms Based Authentication Filtered Content Editor for SharePoint
How to create a Tree View of the Windows Folder and extract all the file-folder info.
How to use AssemblyInfo.cs file in win forms to provide much needed information on Assemblies
Sorting In Datagrid
Helper class to work with NativeMethods in the native api's
Silverlight Line Of Business Applications With Offline WPF Versions
C# : Database monitoring system using XML file
C# : Adding ComboBox to ListView SubItem
Sum of Numbers Captcha: Keeping it Simple
C# Create a Piechart for the specified Hard Disk Drive Utilization
Extension Methods for DataSet and DataTable that makes tasks easier
Accessing IIS Hosted WCF Services from PHP
Helper class that provides most commonly used Extension Methods for DateTime object
Helper class to work with a Status Bar in WPF.
Finding Unmatched Records in Dataset Tables Using Linq
Silverlight Toolkit: Autocomplete TextBox Stock Symbols and Chart
COOL Auto Complete textbox using javascript
Creating a Serializable Log Entry for Microsoft Enterprise Library to log to a Database
ASP.NET Searching Values in Datagrid