RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Creating Usable Page Templates in ASP.NET

Overcome ASP.NET's lack of page templating using this robust and upgradeable templating approach.


ages in Web applications often share common UI components, such as headers, sidebars, and footers. Developers often seek to encapsulate these common components into a page template, which each page can consume and possibly customize. However, in ASP.NET, this can be a nightmare. This is because there is no blunt, intuitive way to structure an application to accomplish page templating. The task becomes even more complicated when pages are large and require nested user controls to organize them into manageable units.

This article shows you how to rise to the challenge of building an effective page templating scheme. As you will see, combining a Web Control that represents the template to the Web designer with a user control that contains the actual template code, you can achieve an elegant yet simple and reusable approach that's easy to maintain and takes full advantage of the ASP.NET framework. This approach becomes especially important when dealing with complex sites containing large data-driven pages that require page-level customization.

Page Template Methods to Avoid
Many developers have invented ad hoc page templating schemes, with mixed results. The most common approaches are discussed below, along with reasons why you should avoid them.

Classic ASP Method. This method is the most archaic, yet most common way of handling page templating in ASP.NET. Developers create include files, containing header and footer content just as they did in classic ASP. Often, you'll find that heavy use of include files is a side effect of migration. While include files still work, you should avoid using them because the include scheme doesn't take advantage of the ASP.NET framework.

Begin-And-End User Control Method. As developers become more familiar with .NET, they often create two user controls, one for header content and one for footer content, usually named something like template_begin.ascx and template_end.ascx. At best, this approach bewilders and confuses the people responsible for page layout, and at worst, it causes errors. Because the opening and closing tags are separated into two files, nesting server-side controls inside the template is not possible—the ASP.NET runtime doesn't allow this. Figure 1 shows a screenshot of the errors generated by Visual Studio .NET when trying to do so. In the end this results in treating the user controls as nothing more than glorified include files, which is really no better than the Classic ASP method.

Thanks for your registration, follow us on our social networks to keep up-to-date