Controlling site design through visual inheritance and page templates

Source: Internet
Author: User
Tags define definition config header inheritance insert object model visual studio
Inherit | control | template | design | page | site
Author: Fritz Onion
Related technologies: templates, Asp.net,master Pages
Difficulty: ★★★☆☆
Reader type: asp.net developer

[Introduction] This article first introduced in the traditional Web development "template" implementation, including ASP and ASP.net 1.x implementation, and then introduced the ASP.net 2.0 template implementation--master pages, finally elaborated the master page realization principle.

For years, Web developers have been trying to "templating" their sites with a variety of technologies, but there is no proven technology that can maintain a truly generic, reusable approach to a standardized look throughout the site. Master pages, one of the most anticipated features available in ASP.net 2.0, ultimately provide a recognized, best-of-breed approach to designing pages based on templates in your application.
Template design
It is pleasing to define a standard appearance for all pages in the Web site design. This may include common headers, footers, and menus, and he can provide a core set of features and skins throughout the site. For dynamic sites that are generated by technologies such as ASP or asp.net, it is useful to consolidate these common features on all pages into a type of page template, which allows individual pages to contain only its own unique content, and provides a central location for site-wide changes in appearance and behavior. For a simple and concrete example of a site that can benefit from some type of page template technology, see Figure 1.


Figure 1 Simple templated site

The particular page has a header at the top, a footer at the bottom, a navigation bar on the left, and an area filled with the rest of the page for the unique content of the pages. Ideally, headers, footers, and navigation bars should only be defined once and applied to all pages in that site in some way.

This is exactly the problem that the master page in ASP.net 2.0 can solve simply and skillfully. By defining a master page and then creating many content pages based on it, you can easily create a site with a common look that is driven by a single template (Master page). Before I explore the details of the master page, however, it would be useful to know how developers can now build a templated site in ASP and ASP.net 1.x.
Generating templates in traditional ASP
Many sites built with ASP 3.0 use the concept of templates-typically using server-side include (SSI) directives. SSI directives provide the ability to insert file content at a specific location within an ASP page. One common technique is to use SSI directives to introduce commonly used elements, such as footers, headers, and navigation bars. Figure 2 illustrates this practice.


Figure 2 server-side include directives in ASP

Although the technology takes a step in the right direction, it still means that each page must generate the surrounding layout elements and the overall structure in addition to all page-specific content. Another way for many sites to be more template-specific is to specify two common include files, such as pagestart.asp and pageend.asp, and make these two files contain not only common navigation bars, headers and footers, but also the surrounding layout elements and the overall page structure. All the elements that are left to each page are unique to it.

This approach provides the control that many developers need in a centralized template across the site, but it also has several drawbacks. First, the designer for editing files containing SSI directives is not supported, so the designer must implement the merged rendering to see the full page appearance, only to be separated later. Second, the inclusion mechanism is too simplistic because it simply inserts the contents of one file into another file before the ASP Analyzer makes server-side calculations. This means that it is easy to make mistakes when matching HTML element end tags and correctly selecting the include location to avoid error rendering. At the same time, it is difficult to customize some parts of the included file. One drawback that you can immediately notice in the ASP "Technique2" example that you can download from the MSDN Magazine Web site is that each page's title is intentionally left blank. This occurs because the title is specified only once in the top-level page_start include file, and there is no ingenious way to have the page containing the template specify what should appear in the header element. Finally, the use of include files requires system overhead because they increase the total size of the ASP script engine cache.

Based on the above simple method of using server-side include directives, the truly generic templating mechanism should ideally have the following five features:
Has a certain function, enabling developers to create a "shell" page that can be defined independently and reused in multiple pages can define the pages that can be used by other pages as templates to change the various elements within the inherited template page, such as changing the caption element to specify an alternate page template declaratively within the page The ability to actually view the rendered version of the page using the template associated with the page
Using the server-side include file with ASP 3.0 satisfies the first of these conditions and can meet the second condition in some way, but cannot provide the last three features.
Generating a templated site in ASP.net 1.x
Asp. NET introduces a new, object-based programming model that is likely to provide a more novel and elegant templating mechanism. Asp. NET provides you with a server-side representation of each page, rather than relying on the lower-level SSI mechanism in ASP 3.0, through a fully hierarchical object model to render to the client element. The functionality that best reflects the SSI file functionality is the user control. User controls provide a declarative way to create custom controls that can insert their content and behavior anywhere else on a page, so using these controls as a common way to define reusable portions of a page is very simple, as shown in Figure 3.


Figure 3 A reusable page section with user controls

In addition to acting as a simple content placeholder, a user control is a complete control that exposes properties, methods, and event features. Unlike server-side include directives, you can give a user control the ability to affect its rendering on the page. For example, you can create a property on a header control named Showbreadcrumbs so that you can selectively turn the breadcrumbs on or off as needed.

However, there are some limitations and drawbacks to the user control reuse model. First, many developers find it cumbersome to add a register directive to each user control in each page that will use the user control. Ironically, many asp.net developers have instead used SSI directives to import the register instruction collection into all their pages, replacing multiple lines of code with only one SSI instruction. More importantly, however, there is no built-in way to use user controls to satisfy any of the five conditions I listed earlier on the development templating mechanism (except the first one, because you can create reusable page parts).

Asp. NET does provide a richer object model, and many people have built their own templating mechanisms to overcome the drawbacks of the lack of native templating mechanisms in the ASP.net 1.x. With a little creativity and some clever coding, you can generate a common templating mechanism. Most implementations rely on the fact that you have the opportunity to manipulate the control hierarchy before the page class is sent back to the client for the control hierarchy that you automatically build. For example, one technique is to create a generic, page-derived base class that can extract controls from the generated page hierarchy, dynamically load the user control that acts as a page template, and then insert the extracted control into a known location in the user control hierarchy. The complete implementation of this technique is included in the code download material for this article.

Using a technique similar to this one can be very close to all five conditions required to achieve a truly useful templating mechanism. Has a user control that defines the portion of a reusable page. has a page template mechanism through which you can define a single template and apply it to any number of pages in your system. Use this technique to define the replaceable element in the template, and you can specify an alternate template for each page. One of the missing features is designer integration-if you don't have visual Studio. NET helps in identifying this templating technology, it is really impossible to implement this feature.
Another drawback to this kind of custom template technology is that there is no accepted way to do this, and there are no built-in components in the. NET framework that support this technology. This means that the templating mechanism used by each site can be completely different.

Although ASP.net provides you with an extremely flexible and powerful programming model, it still does not have a built-in mechanism for templated sites. In particular, although some developers have built templating mechanisms by subtly using control hierarchy substitution and user controls, they still need to complete additional configuration steps and, more importantly, they do not have designer support. This time, let's go into the master page in asp.net 2.0
Master Page
The advent of the master page in asp.net 2.0 represents Microsoft's first templating mechanism to meet all of the conditions I outlined earlier. They provide a site-level page template, a mechanism for fine-grained content substitution, programmatic and declarative control over which template the page should use, and perhaps most notably, they provide integrated designer support. From a technical standpoint, the master page is implemented in much the same way as I described the custom template mechanism in ASP.net 1.1, but with the addition of designer support from Visual Studio 2005, And it is now recognized and supported by visual inheritance to build a templated site, and all of this allows you to eventually have a complete template solution.
The implementation of the master page in ASP.net 2.0 contains two conceptual elements: master pages and content pages. The master page acts as a template for the content page, and the content page provides the content to populate the part of the master page that requires "fill". The master page is essentially a standard asp.net page, except that it uses the extension. master as well as instructions (instead of using). The master page file acts as a template for other pages, so it typically contains top-level HTML elements, main forms, headers, footers, and so on. Within the master page, you can add an instance of the ContentPlaceHolder control where you want the content page to provide page-specific content, as shown in Figure 4.

<!--File:sitetemplate.master-->
<%@ Master language= "C #"%>

<title>
<asp:contentplaceholder runat= "Server" id= "_titlecontent" >
Standard Title
</asp:contentplaceholder>
</title>
<body>
<form runat= "Server" >

<asp:contentplaceholder runat= "Server" id= "_maincontent"/>

</form>
</body>

Figure 4 Adding a placeholder instance

Instead, the content page simply uses the MasterPageFile property to specify the generic. aspx file for the associated master page in its page directives. These pages must contain only instances of the content control, because their only purpose is to provide content for the inherited Master page template. Each content control must map to a specific ContentPlaceHolder control defined in the referenced master page (the content of the control is inserted into the master page placeholder when rendered). The following content page provides content for the Sitetemplate.master master page as shown in Figure 4:

<!--file:default.aspx-->
<%@ page language= "C #" masterpagefile= "Sitetemplate.master"%>

<asp:content contentplaceholderid= "_titlecontent" runat= "Server" >
Main page
</asp:content>
<asp:content contentplaceholderid= "_maincontent" runat= "Server" >
The content for the default page.
</asp:content>

Note that this mechanism allows you to specify the content that you want to place in a very specific location in the master page template. The example just shown shows how to provide a ContentPlaceHolder control within the header element of the master page and a corresponding content control with a matching contentplaceholderid in the contents page. To easily resolve the delicate issue of using templates to generate unique page titles. The example also illustrates how a master page provides default content for a placeholder, so it has a default rendering if the content page decides not to supply a content control for a particular placeholder.


Figure 5 using master pages in asp.net to render pages

After the basic structure of the master page is ready, I can now re-examine the templating examples I generated earlier using other technologies. Recall that the example uses a reusable page content element (the user control in asp.net) to define headers, navigation bars, and footers. Template pages use these elements to lay out a page, while a content page provides internal content for the page. Figure 5 shows the rendering of the example using the master page and content page.


Figure 6 Design support for master pages

The more compelling fact is that the master page can be supported by the designer in Visual Studio 2005, so when you visually edit the content page, it will display the contents of the inherited master page in gray, giving you a clear view of the final rendering of the page. Figure 6 shows how the continuation example of using a master page will look when editing a content page that is attached to my master page.
Implementation Details
As mentioned earlier, master pages and content pages are implemented in much the same way that many developers used to build their own custom templating mechanism in ASP.net 1.x. In particular, the MasterPage class derives from UserControl, thus inheriting the same general-purpose container functionality provided by the user control. Like the custom implementation I discussed earlier, the templates defined by the master page are inserted into the hierarchy of controls generated for the requested page. This insertion occurs just before the Init event of the page class, so that all controls are ready before INIT, which typically performs programmatic manipulation of the control.

Performing a physical merge on the control hierarchy of the master page and the control hierarchy of the page is similar to the way I outlined earlier. The top-level control of the master page, which will have the same name as the file containing the master page, is inserted as the root control into the new page hierarchy. The contents of each content control in the page are then inserted below the corresponding ContentPlaceHolder control as a collection of child controls. Figure 7 shows a sample content page with an associated master page and the resulting merged control hierarchy, which was created before the Init event during page processing. Note the dependencies of different color tags, which indicate the origin of each control in the resulting hierarchy.


Figure 7 Blending levels of master and content pages

One implication of this implementation is that the master page itself is just another control in the page class hierarchy, and you can perform any tasks that you are accustomed to performing on the control directly to the master page. The current master page that is associated with any given page is always available through the master property accessor. As an example of interacting with a master page, you can add code inside the Default.aspx page shown in Figure 7 to programmatically access the HtmlForm that is implicitly added by the master page, as shown in the following code fragment:

void Page_Load (object sender, EventArgs e)
{
HtmlForm f = (HtmlForm) master.findcontrol ("_theform");
if (f!= null)
{
Use f ...
}
}

In addition to accessing master pages, you can change the master page dependencies of a content page at run time. The MasterPageFile property is exposed as a public property on the page class and can be modified within the code of any page. Any modifications to this property must be made in the handler for the new PreInit event of the page class to take effect, because the creation of the master page and the merging with the master page will occur before the Init event is fired. You can add the following Onpreinit method overrides to any page class that uses the master page to programmatically change the master page dependencies:

protected override void Onpreinit (EventArgs e)
{
This. MasterPageFile = "Othertemplate.master";
Base. Onpreinit (e);
}
Detailed usage
When you start using master pages in your site design, if you have never used a site-level templating mechanism, you may experience problems that have not occurred before. The first question relates to the relative path in the referenced resource, such as an image or style sheet. When you create a master page, it is important to remember that a directory that is the starting point when calculating a relative path is likely to change based on the page you are visiting. Consider the directory structure of the site, as shown in Figure 8.


Figure 8 Site Directory structure

If you want to add a reference to the check.gif image in the images directory from the Site.master in the MasterPages directory, you might prefer to add a simple image element, as follows:

<pre class= "Clscode" >


Unfortunately, this method works only if the relative directory location of the page is similar to the location of the image as the master page (such as page1.aspx). No other page (such as Default.aspx) can parse the relative path correctly. One solution to this problem is to use the root path in asp.net to reference syntax, and make sure that all relative references are made from the server-side control, which is the only place that the syntax can take effect. The image reference I mentioned earlier will change to:



Another option is to rely on the fact that relative path references in server-side controls are calculated relative to the master page where they are placed. This means that the image reference can be changed to the following form:



The server-side path reference in the page that references the master page is still relative to the page itself, so you do not have to change any techniques that might be ready to handle the relative references on the page.

Asp. NET developers ' second common request when they first encounter a master page is that they want to be able to require that all pages in the application are content pages that refer to a particular master page. Although this "required" attribute does not exist, you can specify a master page that is used by default for all pages of the application by adding a pages element to the Web.config file to specify a common master page, as shown in the following code fragment:

<!--File:web.config-->
<configuration>
<pages masterpagefile= "~/sitetemplate.master"/>
</configuration>

As with any settings that are specified at the application level, a single page can optionally override the default MasterPageFile property, but if you add the statement to your profile, you can guarantee that any pages that do not have the associated master page are not accidentally added to your application.

Finally, you may find it useful to have a "meta" master page (that is, a master page of a set of master pages). The master page supports nesting at any depth, so you can create any level of master pages that you think are meaningful to your application. As with pages with master pages, master pages with master pages must contain only ContentPlaceHolder controls at the top level. Inside these ContentPlaceHolder controls, the master page can add additional ContentPlaceHolder controls for use by the actual page. Note that a page that references a master page with its own master page can only provide content elements for ContentPlaceHolder controls on a direct parent master page. There is no way to populate a placeholder directly on a master page with a specific page up to level two or more. As an example, take a look at the master page definition (metatemplate.master) shown in the code in Figure 9.

<%@ Master%>

<title>
<asp:contentplaceholder
runat= "Server"
Id= "_titlecontent"
>
Standard Title
</asp:contentplaceholder>
</title>
<body>
<form id= "_theform" runat= "Server" >
<asp:contentplaceholder runat= "Server" id= "_maincontent"/>
</form>
</body>

Figure 9 Master Page definition

You can now define another master page to specify the master page as its master page and to provide content elements for each ContentPlaceHolder control in the parent master page (Sitetemplate.master), as shown in Figure 10.

<%@ Master masterpagefile= "~/metatemplate.master"%>

<asp:content
runat= "Server"
Contentplaceholderid= "_titlecontent"
>
<asp:contentplaceholder runat= "Server" id= "_title" >
Default Title
</asp:contentplaceholder>
</asp:content>

<asp:content
runat= "Server"
Contentplaceholderid= "_maincontent"
>
<table>
<tr>
<td>
<asp:contentplaceholder
Id= "_leftcontent"
runat= "Server"
/>
</td>
<td>
<asp:contentplaceholder
Id= "_rightcontent"
runat= "Server"
/>
</td>
</tr>
</table>
</asp:content>

Figure 10 defines a master page

Note that in order to grant the page access to the _titlecontent placeholder in the parent master page, I must declare a content control and nest a new ContentPlaceHolder control in it to grant the page access to that location in the parent master page.
Summary
Increasing the master page (the long-awaited site-level template feature) in ASP.net 2.0 represents a new era in which Web developers will be able to create Web sites more easily. Developers will no longer have to resort to cumbersome server-side include directives or complex control-hierarchy manipulation techniques in asp.net in ASP. Now, creating a page template that you can base all your other Web pages on is just as easy as designing any other normal type of Web page. I bet you can't wait to move on.

Author: Fritz Onion is an independent consultant, author and trainer specializing in asp.net research. He has essential asp.net (Addison Wesley, 2003) and is working on the second edition of ASP.net 2.0. He prepares and teaches courses for DevelopMentor, and often gives lectures at industry conferences.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.