Design and Implementation Guidelines for Web Clients

Retired Content
This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

 

patterns & practices Developer Center

Microsoft Corporation

November 2003

Applies to:
   Microsoft .NET Framework
   ASP.NET

Summary: This chapter describes how to make ASP.NET code easier to implement and maintain. Chapter 3 describes how to use custom controls to share specific behavior across multiple controls and how to use common page layouts to ensure there is a common appearance across all the pages in your Web site. This chapter also describes how to use inheritance appropriately and effectively in Web applications in order to reuse controls in the presentation layer.

Contents

In This Chapter

Creating New Web Server Controls

Defining Common Page Layouts

Summary

In This Chapter

This chapter describes how to create reusable and maintainable Web interfaces with ASP.NET. The chapter includes the following sections:

  • Creating New Web Server Controls
  • Defining Common Page Layouts

These techniques can simplify ASP.NET Web application development and can help you get consistency across the various pages in your Web application.

Creating New Web Server Controls

ASP.NET provides a wide range of controls that you can use to build your Web applications. However, situations might occur that require you to use specialized controls or to share specific behavior across multiple controls. ASP.NET supports the following two mechanisms for creating new Web server controls:

  • Web user controls
  • Web custom controls

Web user controls are generally more suitable for static layout, and Web custom controls are more suitable for dynamic layout. The following sections describe how to create and use Web user controls and Web custom controls; they also provide recommendations on when to use each approach.

Creating and Using Web User Controls

This section includes the following topics:

  • Overview of Web User Controls
  • Usage Scenarios for Web User Controls
  • Creating Web User Controls
  • Adding Web User Controls to an ASP.NET Web Page
  • Defining Shared Code-Behind Files for Web User Controls

This section provides guidance on how and where to use Web user controls and includes code samples to illustrate key points.

Overview of Web User Controls

A Web user control is a collection of related controls and associated code; it provides a reusable unit that you can add to any ASP.NET Web pages that require this functionality.

In implementation terms, Web user controls are similar to ASPX pages except for the following differences:

  • Web user controls have an .ascx file name extension instead of .aspx. The .ascx file name extension prevents attempts to execute the Web user control as if it were a standalone ASP.NET Web page.
  • Web user controls do not have elements such as <html>, <head> or <body>. These elements are provided by the ASPX Web page that hosts the Web user control.
  • Web user controls can have code-behind files, just like regular ASP.NET Web pages. The class in the code-behind file for a Web user control must inherit from System.Web.UI.UserControl, whereas ASP.NET Web pages inherit from System.Web.UI.Page.

To use a Web user control in an ASP.NET Web page, you must add the .ascx file and its code-behind file to the project. In other words, Web user controls are reused at the source-code level instead of being compiled into reusable assembly files.

When you add a Web user control to an ASP.NET page, the Web user control appears as a placeholder glyph on the page. The constituent controls that make up the Web user control do not appear individually; this means you cannot set their properties directly in the Properties window.

Usage Scenarios for Web User Controls

Web user controls are useful in the following scenarios:

  • You have a collection of related controls that you want to use in several ASP.NET Web pages. You can use the rapid control development features of the Visual Studio .NET Designer to design a Web user control that groups these related controls together.

  • You want to partition an ASP.NET Web page into separate sections so you can define different caching strategies for some parts of the page. For example, if part of the Web page requires you to perform time-consuming database operations, you might want to cache that part of the Web page for a relatively long period of time to improve performance. Web user controls give you the ability to partition Web pages in this fashion, by including an @ OutputCache directive in the .ascx file as shown in the following example.

    <%@ OutputCache Duration="120" VaryByParam="None" %>
    
    
  • You do not have to add the Web user control to the Toolbox. Web user controls cannot be added to the Toolbox because they are not compiled into discrete assemblies. Instead you must copy the Web user control into each application that requires it; this can be disadvantageous if the Web user control is used in many applications.

  • When developers add a Web user control to their ASP.NET Web page, they do not require design-time access to the properties on the individual controls that make up the Web user control.

If these scenarios do not match your requirements, Web custom controls might be more appropriate. For more information, see "Usage Scenarios for Web Custom Controls" later in this chapter.

Creating Web User Controls

The easiest way to create a Web user control is to use the visual support provided by Visual Studio .NET.

To create a Web user control

  1. Open Visual Studio .NET and create an ASP.NET Web application.
  2. In Solution Explorer, right-click the project name. On the shortcut menu, point to Add, and then click Add Web User Control.
  3. Drag controls from the Toolbox onto the Designer to create the visual appearance that you want for your Web user control. By default, the Web user control is in flow layout mode; this means controls are arranged from top-to-bottom and from left-to-right. If you want absolute positioning, first add a Grid LayoutPanel to your Web user control.
  4. Use the Properties window to set the design-time properties for the constituent controls in your Web user control.
  5. Add code to the code-behind class, as follows:
    • Declare public or protected instance variables corresponding to the constituent controls.
    • Initialize the constituent controls in the Page_Load method.
    • Handle events from the constituent controls locally to encapsulate the overall behavior of the Web user control and to maximize its usefulness and reusability by host ASP.NET Web pages.
    • Add public methods and properties to enable external code (such as the host ASP.NET Web page) to configure the appearance of the constituent controls and to get and set their values.

It is also possible to manually create an .ascx file and code-behind files without using Visual Studio .NET.

To manually create an .ascx file and code-behind files

  1. Create a file with an .ascx file name extension.

  2. Add a @ Control directive to the .ascx file, as shown in the following example. For more information about the permitted attributes, see @ Control directive in Visual Studio .NET Help.

    <%@ Control Language="cs" AutoEventWireup="false"
        Codebehind="MyWebUserControl.ascx.cs" Inherits="MyProj.MyWebUserControl"
        TargetSchema="https://schemas.microsoft.com/intellisense/ie5"%>
    
    
  3. Add controls to the .ascx file in the same way that you add controls to an ASP.NET Web page. Do not define <html>, <head>, <body>, or <form> elements, or a <!DOCTYPE> directive.

  4. Create the code-behind file with a file name extension, such as .ascx.cs.

  5. Define a code-behind class that inherits from System.Web.UI.UserControl. Implement the class in the same way that you implement ASP.NET Web pages.

You can convert an existing ASP.NET Web page into a Web user control so that you can reuse it on other pages.

To convert an ASP.NET Web page into a Web user control

  1. Change the file name extension of the ASP.NET Web page file from .aspx to .ascx.
  2. Change the file name extension of the ASP.NET code-behind file (for example, .ascx.cs or .ascx.vb).
  3. Remove the <html>, <head>, <body>, and <form> elements from the .ascx file. Also remove the <!DOCTYPE> directive.
  4. Change the @ Page directive to a @ Control directive in the .ascx file. Also change the Codebehind attribute to refer to the control's code-behind class file (for example, .ascx.cs or .ascx vb).
  5. Remove any attributes that are not supported in the @ Control directive. For a full list of attributes supported in each directive, see @ Page directive and @ Control directive in Visual Studio .NET Help.
  6. Modify the code-behind class so that it inherits from System.Web.UI.UserControl instead of System.Web.UI.Page.

After you create a Web user control, you can add it to ASP.NET Web pages (or to other Web user controls) as described in the next section.

Adding Web User Controls to an ASP.NET Web Page

The easiest way to add a Web user control to an ASP.NET Web page is by using the drag-and-drop capabilities of Visual Studio .NET. In this approach, the Web user control must be implemented in the same language as the host ASP.NET Web page.

To add a Web user control to an ASP.NET Web page

  1. Open Visual Studio .NET and create an ASP.NET Web application.

  2. Add the .ascx file and code-behind file for the Web user control to the project. The Web user control must be implemented in the same language as the host ASP.NET Web page.

  3. Drag the .ascx file from Solution Explorer onto the Designer. The Designer displays a glyph to represent the Web user control, as shown in Figure 3.1. The constituent controls that make up the Web user control do not appear individually, so you cannot edit their properties or visual appearance in the Windows Forms Designer. If you require this capability, consider using Web custom controls instead. For more information, see "Creating and Using Web Custom Controls" later in this chapter.

    Ff647323.f03diforwc01(en-us,PandP.10).gif

    Figure 3.1. Appearance of a Web user control in an ASP.NET Web page

  4. View the HTML markup for the ASP.NET page and notice the @ Register directive. Visual Studio .NET adds this directive when you drag a Web user control onto the Web page. The @ Register directive associates a tag prefix and tag name with the .ascx source file for the Web user control.

    <%@ Register TagPrefix="uc1" 
                 TagName="MyWebUserControl" 
                 Src="MyWebUserControl.ascx" %>
    
    

    Visual Studio .NET also adds an element to represent the instance of the Web user control on your ASP.NET Web page. The tag prefix and tag name (for example, uc1:MyWebUserControl) identify the type of the Web user control. The id attribute (for example, MyWebUserControl1) identifies a particular instance.

    <uc1:MyWebUserControl id="MyWebUserControl1" >
    </uc1:MyWebUserControl>
    
    
  5. Add code to the code-behind file for the ASP.NET Web page as follows:

    • Declare a public or protected instance variable corresponding to the Web user control instance. The variable name must be the same as the id attribute of the Web user control as shown in the following example.

      protected MyWebUserControl MyWebUserControl1;
      
      
    • Write code to interact with the Web user control as required. If the Web user control has public fields for its constituent controls, you can access these controls directly from the ASP.NET Web page. Otherwise, you have to use the methods and properties defined on the Web user control itself.

  6. Build the ASP.NET Web project. The compiler generates a single assembly that contains the compiled code-behind classes for the ASP.NET Web page and the Web user control.

It is also possible to manually add a Web user control by writing code in the HTML file and the code-behind files for the ASP.NET. In this approach, the Web user control and the ASP.NET Web page are compiled separately; therefore, they can be implemented in different languages.

To manually add a Web user control

  1. Copy the .ascx file and code-behind file for the Web user control into an appropriate folder, so that the files can be accessed by the ASP.NET Web page.

  2. Open the .aspx file for the ASP.NET page and add a @ Register directive as follows. The @ Register directive associates a tag prefix and tag name with the .ascx source file for the Web user control.

    <%@ Register TagPrefix="uc1" 
                 TagName="MyWebUserControl" 
                 Src="MyWebUserControl.ascx" %>
    
    
  3. Add an element to represent the instance of the Web user control on your ASP.NET Web page as shown in the following example.

    <uc1:MyWebUserControl id="MyWebUserControl1" >
    </uc1:MyWebUserControl>
    
    
  4. Add code to the code-behind file for the ASP.NET Web page as described earlier.

  5. Compile the source files for the Web user control and the ASP.NET Web page:

    • If the source files are written in the same language, you can compile them into a single DLL assembly as shown in the following example.

      csc /t:library WebForm1.aspx.cs MyWebUserControl.ascx.cs ...
      
      
    • If the source files are written in different languages, you must compile them separately using the appropriate compiler. The following example compiles the Web user control into its own DLL, and then it compiles the ASP.NET Web page by referencing that DLL.

      csc /t:library MyWebUserControl.ascx.cs ...
      vbc /t:library WebForm1.aspx.vb /r:MyWebUserControl.ascx.dll
      
      

To summarize this section on adding Web user controls to an ASP.NET Web page, the easiest approach is to use the drag-and-drop capabilities provided by Visual Studio .NET. The main reason for not using Visual Studio .NET is because you want to use a Web user control that is written in a different language.

Defining Shared Code-Behind Files for Web User Controls

As stated earlier, a Web user control typically comprises two files:

  • An .ascx file; this file defines the visual appearance of the Web user control.
  • A code-behind file; this file provides the functionality of the Web user control.

This division of responsibility between visual appearance and functionality, coupled with the fact that Web user controls are shipped as source files instead of as compiled assemblies, enables you to create shared code-behind files that can be used by several .ascx files. Figure 3.2 illustrates this technique.

Ff647323.f03diforwc02(en-us,PandP.10).gif

Figure 3.2. Using shared code-behind files for Web user controls

Shared code-behind files are useful if you have to define several different user interfaces for the same Web user control. Each user interface is represented by a separate .ascx file; each .ascx file defines its own set of constituent controls as appropriate. The .ascx files are linked to the same code-behind file to reuse the functionality of the code-behind file.

In the code-behind class, you can define instance variables representing the superset of controls that appear in any .ascx file linked to the code-behind file. The following example shows a sample code-behind class for the scenario depicted in Figure 3.2.

public class ControlCode : System.Web.UI.UserControl
{
  protected Control1Type Control1;
  protected Control2Type Control2;
  protected Control3Type Control3;
  ...
}
  

If some of these controls are absent in certain Web user controls, the corresponding instance variable contains a null reference. Therefore, you must look for null references whenever you try to access controls in your code as shown in the following example.

public class ControlCode : System.Web.UI.UserControl
{
  ...
  public void MyMethod1()
  {
    if (Control1 != null)
      ...
  }
}
  

If there are wide differences between the constituent controls defined in each .ascx file, the code-behind class can become unwieldy because it has to cope with all the different user interfaces. Shared code-behind files work best when the .ascx files contain broadly similar sets of controls.

Creating and Using Web Custom Controls

The previous section described how to create Web user controls as a way of reusing portions of user interface code in different ASP.NET Web pages. Web custom controls offer an alternative approach to get the same result.

This section includes the following topics:

  • Overview of Web Custom Controls
  • Usage Scenarios for Web Custom Controls
  • Creating Web Custom Controls
  • Adding Web Custom Controls to an ASP.NET Web Page
  • Defining Alternative User Interfaces for Web Custom Controls

This section describes how Web custom controls differ from Web user controls and provides guidance on how and where to use Web custom controls. Code samples are included to illustrate key points.

Overview of Web Custom Controls

A Web custom control is a compiled component that encapsulates user interface and related functionality into reusable packages. Web custom controls are very different from Web user controls:

  • Web user controls are written using the same programming model as ASP.NET Web pages and are ideal for rapid application development. A Web user control is saved as an .ascx file and is reused by adding the .ascx file to each project that requires it.
  • Web custom controls are compiled components that rely on object-oriented programming features such as inheritance, polymorphism, and encapsulation. A Web custom control is compiled into an assembly and is reused by referencing the assembly in each project that requires it.

You can add Web custom controls to the Toolbox in Visual Studio .NET to simplify reuse of the control at development time. You can also insert Web custom controls into the global assembly cache to share the control between applications and to simplify accessibility of the control at run time.

Usage Scenarios for Web Custom Controls

Web custom controls are useful in the following scenarios:

  • There is an existing ASP.NET Web server control that meets most of your requirements, but you have to add some additional features.
  • None of the existing ASP.NET Web server controls meet your requirements. You can create a completely new Web server control in this scenario.
  • You have a collection of related controls that you want to use in several ASP.NET Web pages. There are two approaches available:
    • Create a Web user control, as described earlier in this chapter. The benefit of this approach is simplicity at design time, because you can visually drag constituent controls from the Toolbox. The disadvantage is limited configurability when you use the control, because you cannot modify properties directly in the Properties window.
    • Create a composite Web custom control. This entails writing a class that inherits directly or indirectly from System.Web.UI.Control, and creates the constituent controls programmatically. The benefit of this approach is flexibility when you use the control, because you can add it to the Toolbox and access properties directly in the Properties window. The disadvantage is complexity at design time, because you must create the control programmatically instead of using ASP.NET-like drag-and-drop techniques.

The following section describes how to create Web custom controls in each of the scenarios described earlier.

Creating Web Custom Controls

You can define Web custom controls to extend the functionality of an existing ASP.NET Web server control.

To create a Web custom control

  1. Create a class library project in Visual Studio .NET and add a reference to the System.Web.dll assembly.
  2. Add a using statement (Imports in Visual Basic .NET) in your code to import the System.Web.UI.WebControls namespace.
  3. Define a class that inherits from the ASP.NET Web server control of your choice.
  4. Define methods, properties, and events as necessary in the new class.
  5. Annotate your class with [Description] attributes to provide design-time information about the class and its members. The [Description] attribute is defined in the System.ComponentModel namespace.

The following example illustrates these points. The example defines a customized text box control that can detect and remove space characters: the CountSpaces property counts the number of spaces in the text, the RemoveSpaces method removes all space characters, and the TextChangedWithSpaces event is generated (instead of TextChanged) if the text changes between postbacks and the new text contains spaces.

using System.Web.UI.WebControls;   // For various Web UI classes
using System.ComponentModel;       // For the [Description] attribute

namespace MyCustomControls
{
  [Description("Space-aware TextBox control")]
  public class MyTextBoxControl : TextBox
  {
    [Description("Fires when the text has been changed, and it contains spaces")]
    public event EventHandler TextChangedWithSpaces;

    [Description("Count of spaces in the text")]
    public int CountSpaces
    {
      get
      {
        int count = 0;
        foreach (char c in this.Text)
          if (c == ' ') count++;
        return count;
      }
    }

    [Description("Remove all spaces from the text")]
    public void RemoveSpaces()
    {
      this.Text = this.Text.Replace(" ", "");
    }

    protected override void OnTextChanged(EventArgs e)
    {
      if (this.Text.IndexOf(" ") != -1)
        this.TextChangedWithSpaces(this, e);
      else
        base.OnTextChanged(e);
    }
  }
}
  

If none of the existing Web server controls provide a suitable baseline for your new control, you can create a completely new Web server control that is not based on an existing control.

To create a completely new Web server control

  1. Create a class library project in Visual Studio .NET and add a reference to the System.Web.dll assembly.
  2. Add a using statement (Imports in Visual Basic .NET) in your code to import the System.Web.UI.WebControls namespace.
  3. Define a new class for your control. If your control renders a user interface, inherit from WebControl; otherwise, inherit from Control.
  4. Optionally implement the following interfaces, as necessary:
    • INamingContainer–This is a marker interface that makes sure the constituent controls have unique IDs.
    • IPostBackDataHandler–This interface indicates that the control must examine form data that is posted back to the server by the client. This interface allows a control to determine whether its state should be altered as a result of the postback, and to raise the appropriate events.
    • IPostBackEventHandler–If a control captures client-side postback events, and handles the events or raises server-side events, the control must implement the IPostbackEventHandler interface.
  5. Define methods, properties, and events as necessary in the new class. For example, if your new control has a user interface, you must write code to render the user interface.

For an example that illustrates these techniques, see "Developing a Simple ASP.NET Server Control" in Visual Studio .NET Help. For more information about how to render a user interface in a Web server control, see "Rendering an ASP.NET Server Control" in Visual Studio .NET Help.

In some situations, you may find it appropriate to develop a composite Web custom control that is an amalgamation of several existing controls.

To develop a composite Web custom control

  1. Create a class library project in Visual Studio .NET and add a reference to the System.Web.dll assembly.
  2. Add a using statement (Imports in Visual Basic .NET) in your code to import the System.Web.UI.WebControls namespace.
  3. Define a new class that inherits from Control.
  4. Implement the INamingContainer marker interface to make sure that the constituent controls have unique IDs in the hierarchical tree of controls on a Web page.
  5. Override the CreateChildComponents method in your class. In this method, create instances of the constituent controls and add them to the Controls collection.
  6. Define methods, properties, and events as necessary in the new class.

For more information about composite controls, see "Developing a Composite Control" in Visual Studio .NET Help. For an example of how to implement custom controls, see "Composite Server Control Sample" in Visual Studio .NET Help.

Adding Web Custom Controls to an ASP.NET Web Page

This section describes how to use a Web custom control in ASP.NET Web pages.

If you intend to use the control in only a small number of ASP.NET Web pages, you can copy the control's DLL assembly into the subfolder for each ASP.NET Web page. If you intend to use the Web custom control in many ASP.NET Web pages, consider adding the control to the global assembly cache to simplify reuse.

The easiest way to reuse a Web custom control is through the Toolbox.

To add a control to the Toolbox

  1. Right-click the Toolbox, and then click Add Tab. Enter an appropriate name for the new tab.
  2. Right-click in the new tab, and then click Add/Remove Items.
  3. In the Customize Toolbox dialog box, click Browse. Locate the DLL assembly for your Web custom control, and then click OK. Verify that the control appears in the list of controls in the Customize Toolbox dialog box.
  4. In the Customize Toolbox dialog box, click OK. Verify that the control appears in the Toolbox.

When you drag a Web custom control from the Toolbox onto an ASP.NET Web page, the Designer displays the actual visual interface for the Web custom control (in contrast to Web user controls, where a placeholder glyph appears instead).

Figure 3.3 shows a Web page that contains various controls, including the custom text box control described earlier.

Ff647323.f03diforwc03(en-us,PandP.10).gif

Figure 3.3. Appearance of a Web custom control in an ASP.NET Web page

You have full design-time access to the properties and events of the Web custom control, as shown in Figure 3.4 and Figure 3.5.

Ff647323.f03diforwc04(en-us,PandP.10).gif

Figure 3.4. Design-time access to the properties of a Web custom control

Ff647323.f03diforwc05(en-us,PandP.10).gif

Figure 3.5. Design-time access to the events of a Web custom control

Figures 3.4 and 3.5 illustrate that Web custom controls are easier to use than Web user controls, because you can use them just like built-in ASP.NET Web server controls in the Designer.

Defining Alternative User Interfaces for Web Custom Controls

If you have to provide alternative user interfaces for a Web custom control, you can use a technique known as skinning to get this effect.

Skinning is similar to the shared code-behind technique discussed in "Defining Shared Code-Behind Files for Web User Controls" earlier in this chapter. Skinning involves defining a Web custom control that has no user interface elements of its own. At run time, load a Web user control to provide the interface (or skin) for the Web custom control.

The Web user control provides only the user interface; it contains no code. The Web user control must define a set of constituent controls with well known names. The Web custom control uses the well known names to obtain references to the constituent controls, and it wires up its own methods to handle control events or assigns its own instance members to the constituent controls.

With this technique, you can mix and match Web custom controls and Web user controls. Different Web user controls can implement subsets of the constituent controls defined in the Web custom control and can use different layouts. The Web custom control must make sure that a constituent control exists before accessing it.

Defining Common Page Layouts

This section describes how to define a common page layout for pages in a Web application. A consistent look makes it easier for users to navigate and use your Web application, and it can simplify application maintenance. It also increases branding and user recognition; these are important factors if your application provides services that compete directly with those of other companies.

The features of a common page layout typically include elements such as headers, footers, menus, and navigation controls. With ASP 3.0, common HTML or script was included into pages using server-side includes. ASP.NET provides a variety of approaches, including:

  • Using a common set of controls
  • Using customizable regions
  • Using page inheritance

The following sections discuss these approaches, including the benefits and disadvantages of each.

Using a Common Set of Controls

Using a common set of controls provides a simple mechanism for making sure there is a consistent look across the pages in a Web application. You must create the individual controls that make up your common layout and put them in a shared location. Each ASPX page references the common set of controls in addition to its custom content.

This is an improvement over ASP server-side includes and ensures that all application pages display the same elementary controls. However, there is no concept of a shared layout; you must define the location of each control separately in each page. Figure 3.6 illustrates two ASP.NET pages that implement a common page layout through the disciplined use of a common set of controls.

Ff647323.f03diforwc06(en-us,PandP.10).gif

Figure 3.6. Using a common set of controls

The requirement to work with each page individually makes this approach suitable only for small ASP.NET applications that have a manageable number of pages and where the overhead of a more elaborate approach would be unwarranted.

Using Customizable Regions

In this approach, you define the common controls and their layout; you also identify a region in the common layout that holds the custom content for each page. There are two frequently used techniques to implement this model, master page and master Web user control.

This section includes the following topics:

  • Using a Master Page
  • Using a Master Web User Control

Using a Master Page

The master page approach requires you to create a single page that you return in response to every user request. The master page defines the common page content and layout of your application. Additionally, this master page defines the region that loads the appropriate contents to satisfy a specific user request.

The content specific to each request is typically defined as a Web user control. Your application identifies the appropriate content to load for each user request using a key; this key is specified in the query string or a hidden field of the user request.

The master page approach makes it easy for you to get a common layout for the pages in your Web application; you have to develop only the individual Web user controls for each of the unique pages. Figure 3.7 illustrates a master page (MasterPage.aspx) that displays custom content based on an ID specified in a query string or hidden field.

Ff647323.f03diforwc07(en-us,PandP.10).gif

Figure 3.7. Using a master page

The main disadvantage of the master page approach is that you cannot use the built-in authorization mechanism provided by ASP.NET to restrict access to each page, because the client always requests the same page. Therefore, you must implement your own authorization mechanism. Additionally, because the client request contains the content key, it leaves your application susceptible to attack.

Overall, the master page approach works best when you have a common layout for your whole application and there are no restrictions on the content that users are permitted to access.

The IBuySpy ASP.NET example application, accessible at https://msdn.microsoft.com/en-us/library/aa286497.aspx, uses the master page approach and includes an example of how to secure individual pages.

Using a Master Web User Control

The master Web user control approach requires you to create a separate .aspx file for every page in your Web application. You also create a Web user control that defines the common page layout and contains an updateable region, such as a table cell, where the dynamic content is inserted. You add the Web user control to every .aspx file that requires the common layout.

Each ASPX page is responsible for defining the content to display in its custom region. For example, a page can set a property on the master Web user control to refer to another Web user control that contains the custom content for that page.

Figure 3.8 illustrates two pages that contain a master Web user control. On each page, the customizable region of the master Web user control is configured to show a different Web user control.

Ff647323.f03diforwc08(en-us,PandP.10).gif

Figure 3.8. Using a master Web user control

The master Web user control approach is best used on small- to medium-sized Web applications, where the cost of developing a more extensive architecture is not warranted. Each Web page corresponds to a separate .aspx file, so you can use the built-in authorization mechanisms of ASP.NET on a page-by-page basis. The main overhead of the master Web user control approach is the requirement to develop the Web user controls that provide the custom content for each page.

Using Page Inheritance

All ASP.NET Web pages compile to classes that inherit from the common base class System.Web.UI.Page. You can take advantage of this support for inheritance as a means to implement a common page layout in your ASP.NET application.

To use page inheritance

  1. Define a class derived from System.Web.UI.Page.
  2. Add controls to the page to create the common layout for all pages that will inherit from this page. Also add a container control, such as a Panel, where derived classes can generate their own content.

Figure 3.9 illustrates the use of page inheritance to implement a common page layout.

Ff647323.f03diforwc09(en-us,PandP.10).gif

Figure 3.9. Using page inheritance

The main advantage of using page inheritance is that it enables you to implement common behavior and common layout; it also provides a convenient way of defining shared helper routines. Also, because each Web page corresponds to a separate .aspx file, you can use the built-in authorization mechanisms of ASP.NET on a page-by-page basis.

The main disadvantage of using page inheritance is increased complexity compared to the other options discussed in this section.

Summary

This chapter described how to create Web user controls and Web custom controls to encapsulate recurring controls in your ASP.NET Web applications.

The choice between using Web user controls or Web custom controls involves a trade-off between simplicity at development time versus flexibility at usage time. Web user controls are easier to develop because they use familiar ASP.NET-like drag-and-drop techniques, whereas Web custom controls must be created programmatically. In contrast, Web custom controls offer more flexibility at usage time because they provide full access to the properties, events, and methods in the Visual Studio .NET Designer.

This chapter also discussed several techniques for creating common page layouts in a Web application. Master Web pages are appropriate if all the pages in the Web application have the same layout and access restrictions. Master Web user controls are more appropriate if you have different access restrictions for the pages in the Web application. Page inheritance is useful if you want to define shared application logic across the pages in the Web application.

Start | Previous | Next

patterns & practices Developer Center

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

© Microsoft Corporation. All rights reserved.