I recently added a new page to my application that is very similar in behavior to a page I had already completed a couple months back.  In fact, the similarities propagate down through the business and data layers as well.  Because of this, I was able to introduce some base classes to limit duplication.  In fact, I started all of this with a generic base test class.

All of the base classes (with generics) were pretty straight forward.  However, generics wouldn't help me when it came to the UI (aspx).  Master Pages would be the tool of choice.  Most of the time when we consider master pages, we think about common presentation, things like navigation and layout.  Being able to easily apply a common presentation template to all of your pages is awesome.  However, master pages go beyond that.

When I was looking at creating this new page, I resisted the urge to reuse code via copy-paste.  I looked at the page I had completed previously and identified those things I could abstract out.  It turns out that there were only a few.  So, I set off to create a master page, where the consumer would fill in the blanks.

I needed one ContentPlaceholder.  That part was easy.  What was a little more involved was getting the consumer of the master page to complete some of the needed behavior.  I decided to use events to allow the master "access" to the consumer.  I think this is a fairly common practice.

After refactoring, my master page was approximately the size (lines of code) of my original page and the original page only required 8 lines in the aspx, and 25 in the code-behind.  Of course, I tested everything multiple times along the way.  Finally, it came time to introduce the new page, which took me less than ten minutes.

If you have a similar need to use master pages for presentation "behavior",
here is a check list of things that might help:
  • Use the <%@ MasterType %> page directive so you do not have to cast Master to your type.
  • Public events on the master are a simple way to hook into the consumer.
  • Register handlers of the master's events in the consumer's Page_PreInit.  This will ensure that the handlers are in place plenty of time before the master needs them.
  • Think twice before you copy-paste your UI code.

Now, I'm going to go see if there are other pages in my application with similar behavior that can be improved with master pages.

posted on Monday, July 28, 2008 5:17 PM
Filed Under [ .Net Design ASP.Net ]


No comments posted yet.

Post A Comment