1. This pattern is “A software design pattern that formalizes the data flow between components by means of an interface”, Microsoft.
  2. Model-view-presenter (MVP) is a user interface design pattern engineered to facilitate automated unit testing and improve the separation of concerns  in presentation logic, Wikipedia.
    • The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.
    • The view is an interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.
    • The presenter acts upon the model and the view. It retrieves data from repositories (the model), persists it, and formats it for display in the view.

For more information on this design pattern check the following article.

Today we will create a simple application which accepts the radius and the color of a circle from the user and then outputs an image with circle drawn to the specifications provided.

When building a application I like to let the user requirements drive the design or of the application therefore I shall start building the application with the user interface (View) and work my way down from there.

The application will be composed of several items:

  • User Interface (Markup)
  • Code Behind for UI
  • View – Interface
  • Presenter

One of the benefits of the MVP pattern is that it allows user interfaces to reuse a presenter despite the user interfaces visually appearing different from each other.

Markup – First thing we do is create our html. To re-create simply create your aspx page and copy and paste the below within your tag

	<div style="float: left; width: 300px;">Radius: Color:</div>
	<p> </p>
	<div style="float: left; padding: 5px; border: 1px dashed gray;">
		<img id="imageCircle" alt="" />

The markup is very simple. A textbox that accepts the radius, a drop down list that will display the colors available, a button to let us know when to perform the action and an image to place the newly created circle. NOTE: No UI validation is perform here. Something simple that can be added a later stage however for expediency & focus on the pattern that has been left out.

Code behind – To re-create simple copy and paste the code below to your code-behind file remembering not to overwrite your class name. Also change the name of the DrawCircle constructor to that of your class.

Within the code behind there are several things happening of note:

  1. The contructor is creating the presenter and passing the view (itself) to the presenters constructor
  2. The Page_Load event & btnDrawCicle_Click events are both offloading the work to the presenter
  3. The IDrawCircleView has been implemented by the DrawCircle class. Notice how the properties interact with the UI elements either setting or getting the values using typed variables.

public partial class DrawCircle : System.Web.UI.Page, IDrawCircleView
	private readonly DrawCirclePresenter _presenter;

	#region Constructor

	public DrawCircle()
		// When creating the page we must at the earliest
		// possible point create the presenter and pass it
		// the view. In this case the view is this page --
		// the page is handing itself to the presenter (IoC)
		// The presenter can take action upon the view during
		// its creation or any time a method within the presenter
		// is called.
		_presenter = new DrawCirclePresenter(this);


	#region Events

	protected void Page_Load(object sender, EventArgs e)
		// We are handing over this event to the
		// presenter as the pattern suggests.
		// NOTE: Not all logic should be passed to the presenter,
		// for instance a browser check, etc.

	protected void btnDrawCircle_Click(object sender, EventArgs e)
		// Hand over the event to the presenter where
		// the work of creating the circle is done, however
		// the presenter hands back and image which we need
		// to show the user.
		// A good example of where the separation of presenter
		// logic and view logic are made.
		using (Bitmap circle = _presenter.DrawCircle())
			using (MemoryStream stream = new MemoryStream())
				circle.Save(stream, ImageFormat.Gif);

				// Base64 Encoded image
				imageCircle.Src = String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(stream.ToArray()));

				// Improve rendering performance
				imageCircle.Width = circle.Width;
				imageCircle.Height = circle.Height;


	#region Implementation of IDrawCircleView

	private float _radius = -1;

	/// Gets the radius of the cirle
	public float Radius { get { if(_radius == -1) _radius = float.Parse(tbRadius.Text); return _radius; } } ///

	/// Gets the diameter of the circle
	public float Diameter { get { return Radius*2; } } 

	/// Gets the selected color 
	public KnownColor CircleColor { get { return (KnownColor)Enum.Parse(typeof(KnownColor), ddlColour.SelectedValue); } } ///

	/// Sets the list of available colors 
	public IEnumerable<KnownColor> Colors { set { ddlColour.DataSource = value; ddlColour.DataBind(); } } 


Note: Implementing IDrawCircleView interface reduces the surface of how the presenter can act on the view. The view controls how clients can interact with it and provides many benefits including easier unit testing.


/// The surface of what is allowable through these properties
/// is quite thin, meaning that only what is needed to satisfy
/// the presenter is put in place. When unit testing however
/// other getters and/or setters may need to be added to make
/// the job easier.
public interface IDrawCircleView { 
	float Radius { get; } 

	// The diameter can be calculated using the
	// radius. This is included to show the possibilities 
	// and just to save time for those consumers that 
	// repeatedly require this. 
	float Diameter { get; } 

	// Use of this type KnownColor instead of Color 
	// simple to have an enum to manipulate rather 
	// than a struct which is what Color is. 
	KnownColor SelectedColor { get; } 

	IEnumerable ColorList { set; } 

	// We declare this with the same signature 
	// as that define within the System.Web.UI.Page class, 
	// cleverly utilizing the existing implementation 
	bool IsPostBack { get; } 

Presenter – The presenter only responds to the user actions and page events (ASP.NET page life cycle) and can only interact with the the UI controls via the View (Interface). Direct interaction with the UI controls are off limits thereby allowing the benefit of changing the UI without having to change the presenter.

public class DrawCirclePresenter
	private IDrawCircleView View { get; set; }

	/// This contructor forces the passing of a view
	/// otherwise it cannot be created.
	public DrawCirclePresenter(IDrawCircleView view) 
		// Just in case the consumer gets smart throw 
		// and exception any time the view is null 
		if(view == null) 
			throw new ArgumentNullException(); 
		View = view; 

	public void Load() { 
		if (!View.IsPostBack) { 
			// This is how we set the list items within the view. 
			// It is always much cleaner and clearer to access 
			// the UI elements through typed properties. In that 
			// case there can be no confusion as to what is expected 
			// or returned. -- Another benefit of using this approach, 
			// however this is not exclusive to the MVP pattern. 
			// Simple converts the list of colors found within 
			// the enum to a list 

			View.ColorList = Enum.GetValues(typeof (KnownColor)).Cast<KnownColor>();

	/// The implementation of this method is not significant to 
	/// understanding how the Model View Presenter design pattern 
	/// works, its just a good demonstration of how to draw an image. 
	public Bitmap DrawCircle() { 
		// Determine size of circle 
		int diameter = (int)Math.Ceiling(View.Diameter); 

		// Create drawing objects 
		Bitmap image = new Bitmap(diameter+6, diameter+6); 
		Graphics g = Graphics.FromImage(image); 

		// Set colors 
		Pen circlePen = new Pen(Color.FromKnownColor(View.SelectedColor), 5); 
		Brush circleBrush = new SolidBrush(Color.IndianRed); 

		// Draw image 
		g.FillEllipse(circleBrush, 3, 3, diameter, diameter); 
		g.DrawEllipse(circlePen, 3, 3, diameter, diameter); 
		return image; 

Through the Load & DrawCircle methods the presenter handles the two events used within the View – Page_Load & btnDrawCircle_Click. While the implementation of the DrawCicle method is not crucial to understanding how the MVP pattern works, it does demonstrate how to create a bitmap on the fly and the btnDrawCircle_Click method demonstrates how to display a dynamically generated image within and ASP.NET page using and img tag.

Please feel free to leave your comments.