Generalities of ASP.NET Server Controls

 

Generalities of ASP.NET Server Controls

All ASP.NET server controls, including HTML and Web controls, plus any custom controls you create or download, descend from the Control class. The class is defined in the System.Web.UI namespace and, as we discussed in Chapter 3, it is also the foundation of all ASP.NET pages. The Control class is declared as follows:

public class Control : IComponent, IDisposable, IParserAccessor,    IUrlResolutionService, IDataBindingsAccessor,    IControlBuilderAccessor, IControlDesignerAccessor,    IExpressionsAccessor 

The IComponent interface defines the way in which the control interacts with the other components running in the common language runtime (CLR), whereas IDisposable implements the common pattern for releasing managed objects deterministically. Table 4-1 explains the role of the other interfaces that the Control class implements.

Table 4-1: Interfaces Implemented by the Control Class

Interface

Goal

IControlBuilderAccessor

Internal-use interface; provides members to support the page parser in building a control and the child controls it contains. Not available in ASP.NET 1.x.

IControlDesignerAccessor

Internal-use interface; provides members to make the control interact with the designer. Not available in ASP.NET 1.x.

IDataBindingsAccessor

Makes the control capable of supporting data-binding expressions at design time.

IExpressionsAccessor

Internal-use interface; defines the properties a class must implement to support collections of expressions. Not available in ASP.NET 1.x.

IParserAccessor

Enables the control to work as the container of child controls and to be notified when a block of child markup is parsed.

IUrlResolutionService

Provides members to resolve relative URLs both at run time and design time. Not available in ASP.NET 1.x.

The IDataBindingsAccessor interface defines a read-only collection the DataBindings property that contains all the data bindings for the controls available to rapid application development (RAD) designers such as Microsoft Visual Studio .NET. Note that the collection of data bindings exists only at design time and, as such, is useful only if you write a RAD designer for the control.

Note 

Compared to ASP.NET 1.x, the base Control class implements many more interfaces. However, only one of them, IExpressionsAccessor, represents some really new functionality. The IExpressionsAccessor interface provides members to retrieve and process custom data-binding expressions a brand new feature of ASP.NET 2.0 that we'll cover briefly in Chapter 9 and that is covered in detail in Programming Microsoft ASP.NET 2.0 Applications: Advanced Topics. All the other interfaces refactor and rationalize control capabilities that exist in ASP.NET 1.x as well.

Properties of the Control Class

The properties of the Control class have no user interface specific features. The class, in fact, represents the minimum set of functionalities expected from a server control. The list of properties for the Control class is shown in Table 4-2.

Table 4-2: Properties Common to All Server Controls

Property

Description

BindingContainer

Gets the control that represents the logical parent of the current control as far as data binding is concerned. Not available in ASP.NET 1.x.

ClientID

Gets the ID assigned to the control in the HTML page. The string is a slightly different version of the UniqueID property. UniqueID can contain the dollar symbol ($), but this symbol is not accepted in ClientID and is replaced with the underscore (_).

Controls

Gets a collection filled with references to all the child controls.

EnableTheming

Indicates whether themes apply to the control. Not available in ASP.NET 1.x.

EnableViewState

Gets or sets whether the control should persist its view state and the view state of any child controls across multiple requests to the configured medium (for example, HTML hidden field, session state, and server-side databases or files).

ID

Gets or sets the name that will be used to programmatically identify the control in the page.

NamingContainer

Gets a reference to the control's naming container. The naming container for a given control is the parent control above it in the hierarchy that implements the INamingContainer interface. If no such control exists, the naming container is the host page.

Page

Gets a reference to the Page instance that contains the control.

Parent

Gets a reference to the parent of the control in the page hierarchy.

Site

Gets information about the container that hosts the current control when rendered on a design surface. For example, you use this property to access the Visual Studio .NET 2005 designer when the control is being composed in a Web form.

SkinID

Gets or sets the name of the skin to apply to the control. A skin is a particular subset of attributes in a theme. Not available in ASP.NET 1.x.

TemplateControl

Gets a reference to the template that contains the current control. Not available in ASP.NET 1.x.

TemplateSourceDirectory

Gets the virtual directory of the host page.

UniqueID

Gets a hierarchically qualified ID for the control.

Visible

Gets or sets whether ASP.NET has to render the control.

The Control class is the ideal base class for new controls that have no user interface and don't require style information.

Identifying a Server Control

The client ID of a control is generated from the value of the UniqueID property the truly server-side identifier that ASP.NET generates for each control. The contents of the ClientID property differ from UniqueID simply in that all occurrences of the dollar symbol ($), if any, are replaced with the underscore (_). Dollars in the UniqueID string are possible only if the control belongs to a naming container different from the page.

ASP.NET generates the value for the UniqueID property based on the value of the ID property that the programmer indicates. If no ID has been specified, ASP.NET auto-generates a name such as _ctlX, where X is a progressive 0-based index. If the control's naming container is the host page, UniqueID simply takes the value of ID. Otherwise, the value of ID is prefixed with the string representing the naming container and the result is assigned to UniqueID.

Naming Containers

A naming container is primarily a control that acts as a container for other controls. In doing so, the naming container generates a sort of virtual namespace so that ASP.NET roots the actual ID of contained controls in the ID of the naming container. To fully understand the role and importance of naming containers, consider the following example.

Imagine you have a composite control that includes a child control say, a button. Entirely wrapped by the outermost control, the button is not directly accessible by the page code and can't be given a distinct and per-instance ID. In the end, the ID of the button is hard-coded in the outermost control that creates it. What happens when two or more instances of the composite control are placed on a page? Are you going to have two button child controls with the same ID? This is exactly what will happen unless you configure the composite control to be a naming container.

The importance of naming containers doesn't end here. Imagine you have two instances of the composite controls named Control1 and Control2, respectively. Imagine also that the embedded button is named Trigger. The full name of the two child buttons will be Control1$Trigger and Control2$Trigger. Suppose you click on the first button and cause the page to post back. If the name of the posting control contains the $ symbol, the ASP.NET runtime recognizes a known pattern: tokenize the name and locate the postback control correctly, no matter its depth in the page tree.

On the other hand, if the button is contained in a control not marked to be a naming container, the ID of the clicked button is not prefixed and will simply be, say, Trigger. In this case, the ASP.NET runtime will look for it as a direct child of the form. The search will obviously fail the button is a child of a top-level control and the postback event will pass unnoticed.

Note 

ASP.NET 2.0 uses the dollar ($) symbol to separate the various parts to form the ID of a control rooted in a naming container. In ASP.NET 1.x, the colon symbol (:) is used for the same purpose.

Binding Containers

In ASP.NET 2.0, a new kind of container is introduced the binding container. The binding container the BindingContainer property indicates which control in the page hierarchy represents the parent of a control as far as data binding is concerned. In other words, the binding container is the control that receives bound data from the host (typically, the page) and that passes it down to child controls.

As you can easily imagine, binding and naming containers often coincide. The only exception is when the control is part of a template. In that case, the NamingContainer property is generally set to the physical parent of the control, namely a control in the template. BindingContainer, instead, will point to the control that defines the template.

Visibility of a Server Control

If you set Visible to false, ASP.NET doesn't generate any markup code for the control. However, having Visible set to false doesn't really mean that no path in the control's code can output text. The control is still an active object that exposes methods and handles events. If a method, or an event handler, sends text directly to the output console through Response.Write, then this text will be displayed to the user anyway. A control with the Visible attribute set to false is still part of the page and maintains its position in the control tree.

Methods of the Control Class

The methods of the Control class are listed and described in Table 4-3.

Table 4-3: Methods of a Server Control

Method

Description

ApplyStyleSheetSkin

Applies the properties defined in the page style sheet to the control. The skin properties used depend on the SkinID property. Not available in ASP.NET 1.x.

DataBind

Fires the OnDataBinding event and then invokes the DataBind method on all child controls.

Dispose

Gives the control a chance to perform clean-up tasks before it gets released from memory.

Focus

Sets the input focus to the control. Not available in ASP.NET 1.x.

FindControl

Looks for the specified control in the collection of child controls. Child controls not in the Controls collection of the current controls that is, not direct children are not retrieved.

HasControls

Indicates whether the control contains any child controls.

RenderControl

Generates the HTML output for the control.

ResolveClientUrl

Use the method to return a URL suitable for use by the client to access resources on the Web server, such as image files, links to additional pages, and so on. Can return a relative path. The method is sealed and can't be overridden in derived classes.

ResolveUrl

Resolves a relative URL to an absolute URL based on the value passed to the TemplateSourceDirectory property.

SetRenderMethodDelegate

Internal-use method; assigns a delegate to render the control and its content into the parent control.

Each control can have child controls. All children are stored in the Controls collection, an object of type ControlCollection. This collection class has a few peculiarities. In particular, it post-processes controls that are added to, and removed from, the collection. When a control is added, its view state is restored if needed and view-state tracking is turned on. When a control is removed, the Unload event is fired.

Events of the Control Class

The Control class also defines a set of base events supported by all server controls in the .NET Framework. Table 4-4 lists these events.

Table 4-4: Events of a Server Control

Event

Description

DataBinding

Occurs when the DataBind method is called on a control and the control is binding to a data source.

Disposed

Occurs when a control is released from memory the last stage in the control life cycle.

Init

Occurs when the control is initialized the first step in the life cycle.

Load

Occurs when the control is loaded into the page. Occurs after Init.

PreRender

Occurs when the control is about to render its content.

Unload

Occurs when the control is unloaded from memory.

All server controls are rendered to HTML using the RenderControl method and, when this happens, the PreRender event is fired.

New Features

In the transition from ASP.NET 1.x to ASP.NET 2.0, server controls gained some new features that are more architectural than programming-related. These new features are the offspring of significant changes that occurred in the underpinnings of the controls.

Adaptive Rendering

Adaptive rendering is the process that enables controls to generate different markup for individual browsers. This result is obtained by delegating the generation of the markup to an external component the adapter. When each control is about to render, it figures out its current adapter and hands the request over to that adapter.

The selected adapter depends on the current browser. The adapter for a control is resolved by looking at the browser capabilities as configured in the ASP.NET browser database. If the browser record includes an adapter class for that control, the class is instantiated and used. Otherwise, the adapter for the control is an instance of the ControlAdapter class. The Control-Adapter class is a generic adapter and simply generates the markup for a control by calling the rendering methods on the control itself.

Note 

The ASP.NET database storing browser information is not a real database. It is, instead, a list of text files with a .browser extension located under the ASP.NET installation folder on the Web server. The exact path is the following: %WINDOWS%\Microsoft.NET\Framework\[version]\CONFIG\Browsers

The data located in this folder is used to return browser capabilities.

A control holds a reference to the mapped adapter instance through the Adapter (protected) property. Each control has an associated adapter unless it is a composite control that defers to its children for rendering.

Browser-Sensitive Rendering

In ASP.NET 2.0, you can declaratively assign a browser-specific value to all control properties. Here's a quick example:

<asp:Button  runat="server" Text="I'm a Button"      ie:Text="IE Button"      mozilla:Text="FireFox Button" /> 

The Text property of the button will contain "IE button" if the page is viewed through Microsoft Internet Explorer and "FireFox button" if the page goes through Firefox. If another browser is used, the value of the unprefixed Text attribute is used. All properties that you can insert in a tag declaration can be flagged with a browser ID. Each supported browser has a unique ID. As in preceding code, ie is for Internet Explorer and mozilla is for Firefox. Unique IDs also exist for various versions of Netscape browsers and mobile devices.

Browser-specific filtering is also supported for master pages. We'll return to this feature in Chapter 6 and present a table with the most common browser IDs. However, browser IDs are interspersed in .browser files, which you can find at the following path:

%windows%\Microsoft.NET\Framework\[version]\CONFIG\Browsers 

XHTML Compliance

XHTML is a World Wide Web Consortium (W3C) standard that defines Web pages as XML documents. This approach guarantees that the elements in the pages are well formed and more forward-compatible with browsers in the near future. By default, the markup produced by ASP.NET 2.0 controls conforms to the XHTML standard with very few exceptions. This compliance with standards produces a number of observable changes in the final markup served to browsers. For example, each element either includes an explicit closing tag or is self-closing (with />) and is always enclosed in a container element. For example, the view state hidden field is now surrounded by a <div> tag, and the name attribute has been removed from the <form> element:

<form method="post" action="default.aspx" > <div>    <input type="hidden" name="__VIEWSTATE"  value=" " /> </div>    ... </form> 

In addition, any script tags rendered into the page include an appropriate type attribute and are rendered in CDATA elements.

It's clear that some of these changes might break existing pages. What if you have a page that relies on the name attribute on the form? To smooth the migration of ASP.NET 1.x pages, you can add the following setting to the web.config file, which forces ASP.NET to render controls as in ASP.NET 1.x:

<system.web>     <XHTML11Conformance enableObsoleteRendering="true" /> </system.web> 

The option to disable XHTML rendering is provided primarily to assist you in upgrading existing pages. You should not abuse it, as it might not be supported in future versions of ASP.NET. Moreover, you should be migrating to XHTML anyway; ASP.NET 2.0 just gives you one more reason to do it now, if possible.

Note 

The generation of XHTML-compliant output is guaranteed only for the vast majority of core ASP.NET server controls. Controls such as HyperLink, BulletedList, and AdRotator generate non-XHTML-compliant markup regardless of the settings you choose. GridView and Tree-View controls are also at risk if they incorporate HyperLinkColumn and TreeNode components. You should avoid using these controls in pages where XHTML compliance is a strict requirement. If you make use of third-party controls, you should always check with the vendor to see whether they generate XHTML markup. Finally, note that ASP.NET is unable to fix XHTML errors that occur in the literal parts of the pages. If your page contains static text or HTML elements, the responsibility of ensuring that they are XHTML-compliant is entirely yours.

How can you make sure that a given page, or a given custom control, renders XHTML markup? You must use a service that runs the page and checks its output. For example, you can use the W3C Markup Validation Service at http://validator.w3.org. You can use the validator in two ways: by entering the URL of your page and having it request and check the page, or by uploading the page to the validator's site.

Themeable Controls

In the ASP.NET 2.0 jargon, a theme is a named collection of property settings that can be applied to controls to make them look consistent across pages. You can apply theme settings to an entire Web site, to a page and its controls, or to an individual control. A theme is identified by name and consists of cascading style sheet (CSS) files, images, and control skins. A control skin is a text file that contains predefined values for some control properties. Applied together, these settings contribute to change the look and feel of the control and give the whole site a consistent (and, you hope, appealing) user interface. In addition, because themes are a sort of monolithic attribute, you can easily export that look from one application to the next. With themes enabled, if the developer adds, say, a DataGrid control to a page, the control is rendered with the default appearance defined in the currently selected theme.

Server controls can dynamically accept or deny theming through a Boolean property named EnableTheming, set to true by default. As a general rule, themes affect only properties that relate to the control's appearance. Properties that explicitly specify a behavior or imply an action should not be made themeable. Each control has the power to state which properties are themeable and which are not. This happens at compile time through attributes in particular, the Themeable attribute. We'll return to themes in Chapter 6. We'll cover custom control development in Programming Microsoft ASP.NET 2.0 Applications: Advanced Topics.

Control State

Some ASP.NET controls require that some state be kept across requests. Examples of this type of state information include the current page of a paged control and the current sort order of a sortable data control. In ASP.NET 1.x, there is only one container in which this data can be stored the view state. However, the view state is mainly designed to maintain settings set by the application, and more important, it can be turned off. What would happen to control-specific state in this case? For this reason, ASP.NET 2.0 introduces the notion of the control state and keeps it separate from the view state to make clear that control state is a vital piece of the control infrastructure.

Control state is a collection of critical view-state data that controls need to function. Because of its critical role, control state data is contained in separate member variables from normal view state and is not affected when view state is disabled. Unlike view state, control state requires extra implementation steps to use.

For one thing, each control needs to signal to the page that it requires control state. Next, there's no unique container to store data, such as ViewState; but the data can be retrieved from any object you want arrays, collections, or a slew of instance variables. Each control persists and loads its control state using a pair of overridable methods, as shown here:

protected override object SaveControlState() protected override void LoadControlState(object state) 

Control state works similarly to view state and is saved and loaded at the same stage of the pipeline that view state is processed. Ultimately, control state is persisted in the same hidden field as the view state.

Input Focus

A useful feature that ASP.NET 1.x lacks is the ability to quickly assign the input focus to a particular control when the page is displayed. This feature can be coded in not much time by a seasoned developer and can be easily engineered into a company-wide framework for building controls and pages.

As we saw in Chapter 3, the Page class of ASP.NET 2.0 provides the SetFocus method to assign the input focus to any control you want. The following code shows how to set the focus to a TextBox control named txtLastName:

void Page_Load(object sender, EventArgs e) {     if (!IsPostBack)         SetFocus("txtLastName"); } 

The SetFocus method caches the ID of the control and forces the Page class to generate ad hoc script code when the page is rendered. Each control can also reclaim the input focus for itself by calling its new Focus method. All controls in the ASP.NET 2.0 Framework benefit from this feature.

 


Programming Microsoft ASP. Net 2.0 Core Reference
Programming Microsoft ASP.NET 2.0 Core Reference
ISBN: 0735621764
EAN: 2147483647
Year: 2004
Pages: 112
Authors: Dino Esposito
BUY ON AMAZON

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net