The ASP.NET Component Model

 

The ASP.NET Component Model

ASP.NET is the key enabling technology for all Web-related functionality provided by the .NET Framework. The .NET Framework is made entirely of an object-oriented hierarchy of classes that span all programming topics for Windows operating systems. Generally speaking, a Web application is made of pages the user requests from a server and that the server processes and returns as markup code mostly HTML. How the requested resource is processed, and therefore how the markup is generated, is server-specific. In particular, when the resource happens to have an .aspx extension, IIS delegates any further processing to the ASP.NET runtime system.

The ASP.NET runtime transforms the source code of the requested .aspx page into the living instance of a .NET Framework class that inherits from a base class named Page. At the end of the day, a running ASP.NET page is an object, and so it is for some of its components the server-side controls.

A large number of new ASP.NET features are just a direct or an indirect propagation of the .NET infrastructure. ASP.NET benefits from cross-language integration and exception handling, garbage collection and code access security, deployment and configuration, and an incredibly rich class library. All these features aren't the products of a self-contained engine, they are available to you because ASP.NET applications are a special breed of a .NET application.

A Model for Component Interaction

Any element in an ASP.NET page that is marked with the runat attribute can be given a unique ID, allowing you to access that element from your server-side code. Accessing items by ID is a natural approach on the client (such as the use of Dynamic HTML pages), but it represents a brand new scheme for server applications. Two factors make this revolutionary approach possible:

  • The component-based architecture of the .NET platform, and the fact that ASP.NET is a constituent part of that platform

  • The ASP.NET built-in mechanism for the application's state management

The component-based design of .NET makes component interaction easy and effective in all environments including ASP.NET applications. ASP.NET components access page features and interact by calling one another's methods and setting properties.

The fact that all elements in the page are true components, and not simply parsable text, provides a flexible and powerful extensibility model. Creating new controls is as easy as deriving a new class; building a page inheritance hierarchy is as easy as specifying a parent class different from the base Page class.

Warning 

Visual Studio .NET 2005 returns a design-time error if you don't explicitly assign each ASP.NET control a unique ID. However, the page will work just fine at run time.

The runat Attribute

The runat attribute is what determines whether a piece of markup text is to be emitted verbatim at render time or transformed into a stateful instance of a particular .NET class. In the latter case, the class would make itself responsible for emitting the related markup. In an ASP.NET page, all markup elements that have the runat attribute set to server are considered server-side controls. The control class exposes methods and properties that let you configure the state of the component. The control is responsible for emitting HTML code when the page is rendered to the browser. Let's consider the following simple code that renders an anchor element in the client page:

Response.Write("<A id=myAnchor href=www.asp.net>Click me</A>") 

The anchor element is created programmatically and is not defined in the page layout. In classic ASP, code blocks and the Response.Write method are the only ways you have to create or configure controls dynamically. In some development environments, such as Microsoft Visual InterDev, design-time controls provided an object-based way to output dynamically generated HTML. Design-time controls, though, were just what the name indicates that is, controls you can use at design-time to generate markup and script code. In ASP.NET, you have a new breed of controls that we could call run-time controls to mark the contrast with design-time controls.

Working with Server-Side Controls

Within an ASP page, there's no way for you to code against the myAnchor element. It's just frozen, lifeless text, only good for sending to the browser. Once on a client, the myAnchor element gets back to life and can accept script instructions. Suppose now that you need to set the href attribute of the anchor based on run-time conditions. In classic ASP, you could first obtain the value for the href attribute and then call Response.Write:

strHref = "http://www.asp.net/" strHtml = "<A id=myAnchor " strHtml = strHtml + "href=" + strHref strHtml = strHtml + ">Click me</A>" Response.Write(strHtml) 

This code will work unchanged in an ASP.NET page but is certainly not the best you can do. By declaring the <A> tag with the runat attribute, you can give life to the anchor element on the server too:

<A runat="server" >Click me</A> 

When the page is loaded, the ASP.NET runtime parses the source code and creates instances of all controls marked with the runat attribute. Throughout the page, the myAnchor ID identifies an instance of the server-side control mapped to the <A> tag. The following code can be used to set the href attribute programmatically when the page loads:

<script runat="server" language="C#"> void Page_Load(object sender, EventArgs e) {     myAnchor.HRef = "http://www.asp.net/"; } </script> 

The markup elements whose name matches an HTML element are mapped to the corresponding HTML server control. Note that not all feasible HTML tags have corresponding ASP.NET controls; for those that don't, a generic control is used. The list of tags and their associated controls is hard-coded in the ASP.NET runtime. Elements that belong to the <asp> namespace are mapped to Web server controls. Other markup elements are mapped to the assembly and class name declared by using an @Register directive.

Pagewide Tags

The runat attribute can be used also with pagewide tags such as <head> and <body>. These tags are represented through an instance of the HtmlGenericControl class. HtmlGenericControl is the .NET class used to represent an HTML server-side tag not directly represented by a .NET Framework class. The list of such tags also includes <span>, <font>, and <iframe>.

In the following page, the background color is set programmatically when the page loads:

<%@ Page Language="C#" %> <script runat="server"> private void Page_Load(object sender, EventArgs e) {    TheBody.Style[HtmlTextWriterStyle.BackgroundColor] = "lightblue"; } </script> <html> <body  runat="server">    <h3>The background color of this page has been set programmatically.        Open View|Source menu to see the source code.</h3> </body> </html> The resulting HTML code is as follows: <html> <head><title>Pro ASP.NET (Ch 01)</title></head> <body  style="background-color:lightblue;"> <form method="post" action="Body.aspx" >   <div>     <input type="hidden" name="__VIEWSTATE" value="/wEPD  RVC+" />   </div>   <h3>The background color of this page has been set programmatically.       Open View|Source menu to see the source code.</h3> </form> </body> </html> 

Likewise, you can set any of the attributes of the <body> tag, thus deciding programmatically, say, which style sheet or background image to use. You use the HtmlGenericControl's Attributes collection to create attributes on the tag. You use the InnerText property to set the inner text of a tag.

TheBody.Attributes["Background"] = "/proaspnet20/images/body.gif"; 

We'll discuss the programming interface of the HtmlGenericControl class in more detail in Chapter 4.

Note 

In ASP.NET 2.0, the contents of the <head> tag can be accessed programmatically as long as it is flagged with the runat attribute. The Page class exposes a bunch of ad hoc methods and properties that we'll explore in Chapter 3.

Unknown Tags

In case of unknown tags, namely tags that are neither predefined in the current schema nor user-defined, the ASP.NET runtime can behave in two different ways. If the tag doesn't contain namespace information, ASP.NET treats it like a generic HTML control. The empty namespace, in fact, evaluates to the HTML namespace, thereby leading the ASP.NET runtime to believe the tag is really an HTML element. No exception is raised, and markup text is generated on the server. For example, let's consider the following ASP.NET page:

<%@ Page Language="C#" %> <script runat="server"> void Page_Load(object sender, EventArgs e) {     dinoe.Attributes["FavoriteFood"] = "T-bone steak"; } </script> <html> <head><title>Pro ASP.NET (Ch 01)</title></head> <body> <form runat="server">   <Person  runat="server" />   Click the <b>View|Source</b> menu item... </form> </body> </html> 

The <Person> tag is still processed as if it was a regular HTML tag, and the FavoriteFood attribute is added. Figure 1-4 shows what the HTML code for this page actually is. In the preceding sample, the type of the dinoe object is HtmlGenericControl.

image from book
Figure 1-4: ASP.NET also processes namespace-less custom tags, mapping them to the HtmlGenericControl class.

If the tag does contain namespace information, it is acceptable as long as the namespace is <asp> or a namespace explicitly associated with the tag name using an @Register directive. If the namespace is unknown, a compile error occurs.

ASP.NET Server Controls

There are basically two families of ASP.NET server controls. They are HTML server controls and Web server controls. System.Web.UI.HtmlControls is the namespace of HTML server controls. System.Web.UI.WebControls groups all the Web server controls.

HTML Server Controls

HTML server controls are classes that represent a standard HTML tag supported by most browsers. The set of properties of an HTML server control matches a commonly used set of attributes of the corresponding tag. The control feature properties such as InnerText, InnerHtml, Style, and Value plus collections such as Attributes. Instances of HTML server controls are automatically created by the ASP.NET runtime each time the corresponding HTML tag marked with runat="server" is found in the page source.

As mentioned, the available set of HTML server controls doesn't cover all possible HTML tags of any given version of the HTML schema. Only most commonly used tags found their way to the System.Web.UI.HtmlControls namespace. Tags such as <iframe>, <frameset>, <body>, and <hn> have been left out as well as less frequently used tags such as <fieldset>, <marquee>, and <pre>.

The lack of a specialized server control, however, doesn't limit your programming power when it comes to using and configuring those tags on the server. You only have to use a more generic programming interface the HtmlGenericControl class, which we looked at briefly in this section.

Web Server Controls

Web server controls are controls with more features than HTML server controls. Web server controls include not only input controls such as buttons and text boxes, but also special-purpose controls such as a calendar, an ad rotator, a drop-down list, a tree view, and a data grid. Web server controls also include components that closely resemble some HTML server controls. Web server controls, though, are more abstract than the corresponding HTML server controls in that their object model doesn't necessarily reflect the HTML syntax. For example, let's compare the HTML server text control and the Web server TextBox control. The HTML server text control has the following markup:

<input runat="server"  type="text" value="Dino" /> 

The Web server TextBox control has the following markup:

<asp:textbox runat="server"  text="Dino" /> 

Both controls generate the same HTML markup code. However, the programming interface of the HTML server text control matches closely that of the HTML <input> tag, while methods and properties of the Web server TextBox control are named in a more abstract way. For example, to set the content of an HTML server text control you must use the Value property because Value is the corresponding HTML attribute name. If you work with the Web server TextBox control, you must resort to Text. With very few exceptions (that I'll discuss in Chapter 3), using HTML server controls or Web server controls to represent HTML elements is only a matter of preference and ease of development and maintenance.

 


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