Model View Presenter in ASP.NET 2.0
Martin Fowler is introducing several new enterprise patterns for his new book. My attention was captured by the Model View Presenter pattern and I immediatly tryied to apply it in a simple ASP.NET 2.0 (version 8.0.40607.85) web form with a CheckBox, a TextBox a Button and a Label. the use case is really simple, I can edit into the textbox and save what it written into the label throught the button click event. If the checkbox is checked I can't edit anymore. [note: in this basic sample I don't have a domain object].
So, my partial class (of the view) will be:
public partial class MyView_aspx
{
MyPresenter pmod = null;
void Page_Load(object sender, EventArgs e)
{
pmod = new MyPresenter(this);
}
void cbEditMode_CheckedChanged(object sender, EventArgs e)
{
pmod.SetEditMode(cbEditMode.Checked);
}
void BtnLoad_Click(object sender, EventArgs e)
{
pmod.Save();
}
}
and the presenter will be:
public class MyPresenter
{
Page _form;
public MyPresenter(Page form)
{
_form = form;
}
public void SetEditMode(bool isEditMode)
{
TextBox txtName = (TextBox)_form.FindControl("txtName");
txtName.ReadOnly = isEditMode;
}
public void Save()
{
TextBox txtName = (TextBox)_form.FindControl("txtName");
Label lblName = (Label)_form.FindControl("lblName");
lblName.Text = txtName.Text;
}
}
The code isn't perfect because I have to resolve the form controls at each call. The optimization could be to reference the view class (MyView_aspx) into the Presenter constructor, but this isn't possible (even if the Presenter lives in the same assembly of the web application) in this build (MS folks, is it by design or it will be possible in beta 2 ?).