Monday, August 31, 2009

Simple MVP in ASP.NET

Model View Presenter (MVP)

The model:

public interface IEntity
{
SomeType SomeProperty1 { get; set;}
SomeOtherType SomeProperty2 { get; set;}
YetAnotherType SomeProperty3 { get; set;}
}



The interface (the view contract - insulates the presenter from the implementation):

public interface IEntityView
{
event EventHandler Init;
event EventHandler Load;
event EventHandler Unload;
IEntity Entity { get; set; }
bool Visible { get; }
}


The code behind (the view implementation):

public partial class EntityDisplayPage : Page, IEntityView
{
protected EntityDisplayPage()
: base()
{
new EntityPresenter(this); // wire the MVP pattern
}

#region IEntityView Members

public IEntity Entity { get; set; }

#endregion
}


The presenter (doesn't know the view implementation, manipulates it through the view contract defined as an interface):

public class EntityPresenter
{
public EntityPresenter(IEntityView view)
: base()
{
if (null == view)
throw new ArgumentNullException("view");
this.view = view;

this.View.Init += (sender, e) => { /* some business logic on init */ };
this.View.Load += (sender, e) =>
{
/* some business logic on load*/
this.View.Entity = GetEntityToDisplay();
};
this.View.Unload += (sender, e) => { /* some business logic on unload*/ };
}

private readonly IEntityView view;
public IEntityView View
{
get { return view; }
}
}


And that's how you get good separation through a simple MVP implementation in ASP.NET. I think it speaks for itself.

No comments: