MVP design pattern of ASP.NET

Posted: June 9, 2011 in ASP.NET

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.

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

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.

Start with the aspx page (View). Add a label, a button and a TextBox.

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 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 setInfo()
{
List l = new List();
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 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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s