Page Controller Pattern in ASP.NET

The Page Controller pattern is perhaps the simplest way to add MVC to your web apps.

A Page Controller is one object or file declaration designed to handle the request for one logical web page or action.

That’s the simplest way to explain it. So how exactly does it map to ASP.NET? Quite easily, as it turns out:

  • Model: Your business class (ie; a User class)
  • View: A UserControl
  • Controller: Your code-behind class for the requested page

From Martin Fowler’s Patterns of Enterprise Application Architecture:

The basic responsibilites of a Page Controller are:

  1. Decode the URL and extract any form data to figure out all the data for the action.
  2. Create and invoke any model objects to process the data. All relevant data from the HTML request should be passed to the model so that the model objects don’t need any connection to the HTML request.
  3. Determine which view should display the result page and forward the model information to it.

This sounds simple enough, and in fact it is. So how does it work, exactly? Well, let’s say we want to display the information regarding a specific User within our system. We’ll first need to have a User class, with it’s requisite properties (ie; FirstName, LastName, etc). We’ll also need a UserControl to display the user’s details. This UserControl will have a property called BoundEntity, which holds an instance of the User class it is to display. The job of the Page Controller (our .aspx code-behind file) is to figure out which user needs to be displayed, fetch their details from the data store, pass the User to the UserControl, and then load the UserControl for display. Here’s how it could look:

private void Page_Load(object sender, System.EventArgs e)
{
     LoadEntity();
}
 
private void LoadEntity()
{
     User user = new User();
     if( this.RequestedEntityID > 0 )
     {
           user.ID = this.RequestedEntityID;
           BrokerFactory.Fill( user );
      }
      EntityControl cont = 
(EntityControl)LoadControl( "EditStaff.ascx" );
      cont.BoundEntity = user;
      this.phEntity.Controls.Add( cont );
}

So, as you can see, we’ve grabbed the id from the querystring (through the call to RequestEntityID, which is a property of the base page class), and if the ID is greater than zero, we load the User from the database. We then create the desired View by instaniating the correct UserControl, assign the User object to the control, and then finally add the UserControl to a PlaceHolder control on the actual aspx page.