Add post-backs to MVC –or- add front controller to Web Forms

Lots of programmers I talk to are managing software assets written in ASP.NET. These applications have been in production for years, and they work. The problem that is pervasive among all of them is that the Page_Load method is much too large. Model-View-Presenter is fatally flawed as a pattern because the view obtains control before the presenter does. This wrong ordering is an unrecoverable error in the workability of the pattern. I have spent a number of years attempting to implement the MVP pattern well before I came to this conclusion.

This post contains a short example that inserts a controller in the request pipeline before the Web Form. This allows large and bloated Page_Load methods to offload a bit of logic to a controller that executes in front of the Web Form. Interestingly enough, this same technique allows an ASP.NET MVC page to leverage post-backs and server side controls.

Here is the solution view:

Default.aspx.controller.cs is the controller that executes ahead of Default.aspx. The Visual Studio tooling doesn’t know to nest this file like I would like it.

Here is the page run the first time:

And here is the page after 3 clicks on the button that is an <asp:Button/>

Notice that I overrode the Execute method. In this case, there is no need for the concept of an action. We merely have an object that executes before the Web Form. Then the controller builds the Web Form and asks it to process the request.

Half of this method could easily be factored into another class, but it works very simply. I did not have to jump through any hoops. I hammered out this code in about 10 minutes.

If your Page_Load methods are getting too long, consider putting a front controller in front of the page.

Related

Jim
11:47 am on March 16, 2010

How would you implement a unit test against this code. It seems like there is a lot of coupling in the Execute Method. For instance: System.Web.HttpContext.Current