HtmlControls

I l @ ve RuBoard

The HtmlControls all inherit from System.Web.UI.HtmlControls.HtmlControl , and are the most basic server controls in the Framework. Any HTML tag can be made into an HtmlControl simply by adding runat ="server" to it. There are about a dozen HtmlControls that have specific behavior, and thus have their own subclassed classes to describe them. Any other control is created as an HtmlGenericControl class . Figure 5.1 demonstrates the class hierarchy for the HtmlControls.

Figure 5.1. HtmlControls class hierarchy.

HtmlControl Properties and Methods

Because all HtmlControls inherit from the System.Web.UI.HtmlControls.HtmlControl class, its properties and methods are available to all HtmlControls, described in Table 5.1. The next sections introduce a few of the more commonly used attributes of this class.

Table 5.1. Summary of HtmlControl Properties and Methods
Name Inherited Item Description
Attributes : AttributeCollection   Property Returns a collection of name-value pairs that map to attributes of the HTML tag. Used for custom attributes that are not valid HTML and HTML attributes not exposed by a control's properties.
ClientID : String Yes Property Returns the server control identifier created by ASP.NET.
Controls : ControlCollection Yes Property Returns a collection of the child controls of the current control.
Disabled : Boolean   Property Sets or returns whether or not the HtmlControl is disabled. Defaults to false.
EnableViewState : Boolean Yes Property Sets or returns whether or not the HtmlControl should retain its value between page postbacks. Defaults to true.
ID : String Yes Property The programmatic identifier of the control. Can be set with id= in the control's declaration.
Style :   Property Returns a CssStyleCollectionCssStyleCollection that holds CSS style properties for the HtmlControl.
TagName : String   Property Returns the name of the HTML element that was used to create this HtmlControl, such as "b" or "form".
Visible : Boolean Yes Property Returns or sets whether or not the control should be displayed when the page is rendered. Defaults to true.
DataBind : Void Yes Method Binds a datasource to the control and its child controls.
FindControl : Control Yes Method Searches the current naming container for a control with the ID provided, and returns that control if found.
HasControls : Boolean Yes Method Returns true if the HtmlControl contains any child controls, otherwise returns false.

The properties and methods marked "Yes" in the Inherited column are properties and methods of HtmlControl that it inherits from the System.Web.UI.Control class. These properties and methods are a part of every control, whether it is an HtmlControl, a WebControl, or a custom control that you write yourself (custom controls are covered in Chapter 12, Custom ASP.NET Controls).

HtmlContainerControl Properties

As we saw in Figure 5.1, many HtmlControls inherit from another base class, HtmlContainerControl (which in turn inherits from HtmlControl ). These controls represent HTML elements that are made up of both starting and ending tags, with content in between, such as <table>...</table> or <a>...</a> . As such, they are said to contain additional HTML, and to access their contents, they expose two properties as described in Table 5.2.

Table 5.2. HtmlContainerControl Properties
Property Description
InnerHtml : String Gets or sets all of the content found between the opening and closing tags of the HtmlControl.
InnerText : String Gets or sets the text between the opening and closing tags of the HtmlControl. Automatically encodes special characters (such as " < " or " > ") so that they are displayed on the page as typed (for example, " &lt; " or " &gt; "). If you need to add HTML content, use the InnerHtml property.

An HtmlControl Example

The easiest way to get a quick handle on how HtmlControls work is through an example. In one page, we will use every HtmlControl. To demonstrate how the controls are created by ASP.NET based on these HTML tags, we will use an ASP.NET feature called Tracing, which will be covered in more detail in Chapter 13, "Debugging ASP.NET Overview." As part of the Trace output, you can see the Control Tree, which describes all of the controls created on the page, and how they are nested within one another. Figure 5.2 shows the output of the page, without the trace.

Figure 5.2. HtmlControls demo page.

As you can see, this sample page makes use of many different HTML elements, such as images, links, buttons, radio buttons , check boxes, and drop-down lists. All of these HTML elements have corresponding HtmlControls, as Figure 5.3 demonstrates.

Figure 5.3. HtmlControls demo page Control Tree.

Examining the Control Tree in the trace output, we see that the first HtmlControl on the page has the ID of htmltag , and is an HtmlGenericControl . There are several of these generic controls, including headtag , titletag , and H1Title , which are simply HTML tags with runat="server" added to them, but which don't have any special object behavior. Because there are dozens of legal elements defined in the HTML specification, but many whose behavior is not particularly different from many other tags, the HtmlGenericControl provides the programmatic interface to all of these tags. The HtmlGenericControl only exposes one property in addition to the ones described in the HtmlControl and HtmlContainerControl classes, and that is the TagName property. TagName is a String that can be used to get or set the name of the element that the HtmlGenericControl represents. For instance, the TagName of the tag <a href='foo'> is 'a' .

Also note the many LiteralControl controls on the page. These are placed between any HtmlControls that could have additional HTML content between them (which is between almost every control). Note that because there is no valid HTML that can be placed between a <tr> tag and its child <td> tags, there are no LiteralControls wrapping these tags.

Looking at Listing 5.1, you will notice that the HtmlGenericControls all correspond to HTML tags that have had the attribute runat="server" added to them, along with an ID attribute. If no ID is specified, ASP.NET will assign one.

Listing 5.1 HtmlControlsDemo.aspx.
 <%@ Page language="c#" Codebehind="HtmlControlsDemo.aspx.cs" AutoEventWireup="false" Inherits="Html_Web_Controls.HtmlControlsDemo" Trace="True"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML runat="server" id="htmltag">   <HEAD id="headtag" runat="server">     <title id="titletag" runat="server">HtmlControls</title> </HEAD>   <body >     <h1 runat="server" id="h1Title">HtmlControls</h1>     <form id="Form1" method="post" runat="server">         <table runat="server" id="table1">         <tr runat="server" id="row1">             <td runat="server" id="cell1">                 <span runat="server" id="span1">Span</span>             </td>             <td runat="server" id="cell2">                     <input id="input1" runat="server"                         value="input1">             </td>             <td runat="server" id="cell3">                 <input id="radio1" runat="server"                     type="radio" value="Choice 1" >                 <input id="radio2" runat="server"                     type="radio" value="Choice 2" >             </td>             <td runat="server" id="cell4"><input type="button"             runat="server" id="button1" value="Button" ></td>         </tr>         <tr runat="server" id="row2">             <td runat="server" id="cell5">                 <select runat="server" id="select1">                     <option >Option 1</option>                     <option >Option 2</option>                 </select>             </td>             <td runat="server" id="cell6">                 <textarea runat="server" id="textarea1"></textarea>             </td>             <td runat="server" id="cell7">                 <a runat="server" id="anchor1"                     href="http://aspsmith.com/">                     <img                     src="http://aspsmith.com/images/aspsmith_logo_197x53.gif"                         runat="server" id="image1" >                 </a>             </td>             <td runat="server" id="cell8">                 <input type="checkbox" runat="server"                     id="check1" value="choice 1" name="check1">                 <input type="checkbox" runat="server"                     id="check2" value="choice 2" name="check2">             </td>         </tr>         </table>         <input type="hidden" runat="server" id="hidden1">         <input type="file" runat="server" id="file1" >         <input type="image" runat="server" id="imagebutton1"         alt="Input type=image"         src="http://aspsmith.com/images/aspsmith_logo_197x53.gif">     </form>   </body> </HTML> 

HtmlForm Properties

Looking once more at Figure 5.3, we see that the first nongeneric HtmlControl on the page is Form1 . Form1 is an HTML form tag, and is represented by the HtmlForm class, which has several properties specific to it, described in Table 5.3.

Table 5.3. HtmlForm Properties
Property Description
Enctype : String Gets or sets the encoding type. The default is application/ x-www-form-urlencoded . File upload forms should use multipart/form-data .
Method : String Gets or sets a value that indicates how the browser posts form data. The two most common methods are GET and POST . The default is POST .
Name : String Gets or sets the identifier name of the control. Identical to the UniqueID property.
Target : String Gets or sets the value that represents the frame or window where the form's output should be sent. Not required for typical postback operations.

It is interesting to note that the HtmlForm control does not have an Action property, which is a valid attribute of the <form> tag in HTML. The Action attribute specifies a URL to which the form should be posted. ASP.NET's event model is designed around the concept of pages that post back to themselves , and so if a page needs to submit data to another page, it should simply use an HTML form tag and no server controls. In most situations, multiple pages are not needed, and a single page using postbacks and redirects will work.

Table Control Properties

Continuing with our walkthrough of Figure 5.3, the next controls we encounter after Form1 are table1 , row1 , and cell1 . These controls are instances of HtmlTable , HtmlmTableRow , and HtmlTableCell classes, respectively. These controls are, not surprisingly, used to represent HTML table structures. As such, they expose a number of properties that are useful in formatting these tables, and basically map directly to HTML attributes (see Table 5.4).

Table 5.4. Table Control Properties
Class Properties (String unless noted)
HtmlTable
 Align, BgColor, Border : Int32, BorderColor, CellPadding : Int32, CellSpacing : Int32, Height, Rows : HtmlTableRowsCollection, Width 
HtmlTableRow
 Align, BgColor, Border, BorderColor, Cells: HtmlTableCellCollection, Height, Valign 
HtmlTableCell
 Align, BgColor, Border, BorderColor, ColSpan : Int32, Height, NoWrap : Boolean, RowSpan : Int32, VAlign, Width 

Using these properties, it is very easy to programmatically alter the formatting of tables and their contents. For instance, adding these lines to the Page_Load event of the HtmlControlsDemo.aspx.cs page (the codebehind page for HtmlControlsDemo.aspx), which is executed whenever the page is loaded

  private void Page_Load(object sender, System.EventArgs e) {     // Put user code to initialize the page here     table1.Border = 2;     row1.BorderColor = "red";     cell1.BorderColor = "blue"; } 

results in this HTML output:

  <table id="table1" border="2"> <tr id="row1" bordercolor="red"> <td id="cell1" bordercolor="blue"> ... 

HtmlInputControl Properties

Continuing on with the sample page, the next new controls we encounter are input1 , an HtmlInputText control, radio1 and radio2 , a pair of HtmlInputRadioButton controls, and button1 , an HtmlInputButton . All of these controls inherit from the HtmlInputControl base class, which exposes the three properties described in Table 5.5, in addition to those of its parent, HtmlControl .

Table 5.5. HtmlInputControl Properties
Property Description
Name : String Same as for HtmlForm.
Type : String Gets the type of the control. Possible values include button , checkbox , file , hidden , image , password , radio , reset , submit , and text .
Value : String Gets or sets the contents of the control.

The HtmlInputText control simply displays a text box, and exposes integer properties of MaxLength and Size that map directly to the HTML attributes of the same name. The HtmlInputRadioButton control renders to a radio button, and includes a Boolean property Checked that can be read or set. In addition, the HtmlInputText and HtmlInputRadioButton controls both have an event, ServerChange , that is raised whenever the value of the control changes. When this event occurs, if there is a corresponding event handler function set up in the ASP.NET page, that function will be executed in response to the event. This is what allows ASP.NET to use an event-driven programming model, as opposed to the more procedural programming model of ASP.

The HtmlInputButton control maps to an HTML button, and has one new property, CausesValidation , which is Boolean. This property defaults to true, and determines whether or not clicking on this button should cause validation controls to be activated. We will cover validation controls in Chapter 8, "Using ASP.NET Validation Controls." The HtmlInputButton also raises an event, ServerClick , which occurs when the button is clicked.

HtmlSelect Properties

Moving to row two of our sample page, we find controls for HtmlSelect , HtmlTextArea , HtmlAnchor , HtmlImage , and HtmlInputCheckBox . Of these, the HtmlSelect control is the most complicated, primarily because it can be populated automatically from a data source using data binding. It exposes the properties described in Table 5.6.

Table 5.6. HtmlSelect Properties
Property Description
DataSource : Object Gets or sets the object to be used as the data source for this control.
DataTextField : String Gets or sets the name of the field in the data source that will provide the text for each option in the list.
DataValueField : String Gets or sets the name of the field in the data source that will provide the value for each option in the list.
InnerHtml : String Same as for HtmlContainer .
InnerText : String Same as for HtmlContainer .
Items : ListItemCollection A collection of ListItems that make up the options in the selection list.
Multiple : Boolean Gets or sets a value indicating whether multiple values in the selection list can be selected. Defaults to false.
Name : String Same as for HtmlForm.
SelectedIndex : Int32 Gets or sets the zero-based index of the selected list item.
SelectedIndices : Int32 Array Gets or sets an array of integers, each of which represents a selected item in the option list.
Size : Int32 Gets or sets a value corresponding to the number of options to list on a page at a time. Defaults to 1.
Value : String Gets or sets value of the currently selected item.

We'll look at some different ways of populating select lists later in this chapter. For this example, you can see that we simply added <option> tags just as we normally would on an HTML page. In addition to the properties listed in Table 5.6, the HtmlSelect control also has one event, ServerChange , which is fired whenever the selected item of the list changes.

HtmlTextArea Properties

The HtmlTextArea control, textarea1 , is the next one we see in our example, and Table 5.7 describes the properties unique to it.

Table 5.7. HtmlTextArea Properties
Property Description
Cols : Int32 Gets or sets the number of columns the control should have. Maps directly to HTML attribute.
Name : String Same as for HtmlForm.
Rows : Int32 Gets or sets the number of rows the control should have. Maps directly to HTML attribute.
Value : String Gets or sets the value of the contents of the textarea box.

HtmlAnchor Properties

The Anchor tag is probably one of the most commonly used HTML tags, and it exposes several properties unique to the HtmlAnchor control, as described in Table 5.8.

Table 5.8. HtmlAnchor Properties
Property Description
Href : String Gets or sets the URL target of the link.
Name : String Same as for HtmlForm.
Target : String Same as for HtmlForm.
Title : String Provides a tool tip for the link on the page.

Again, these properties pretty much just map to HTML attributes. The Anchor tag also supports one event, ServerClick , which is fired whenever a user clicks on the link.

HtmlImage Properties

The HtmlImage control maps to the HTML <img> tag, and has the properties described in Table 5.9.

Table 5.9. HtmlImage Properties
Property Description
Align : String Gets or sets the alignment of the image relative to other elements on the page. Valid values include left, center, right, top, middle, and bottom.
Alt : String Gets or sets the caption displayed if the image is unavailable or the user moves their mouse over the image.
Border : Int32 Gets or sets the width, in pixels, of the image's border.
Height : Int32 Gets or sets the height of the image, in pixels.
Src : String Gets or sets the URL of the image file to be displayed by this control.
Width : Int32 Gets or sets the width of the image, in pixels.

All of the HtmlImage properties map directly to HTML attributes. The last HtmlControl we see in this row of the table is the HtmlInputCheckBox . The HtmlInputCheckBox supports one new property, Checked , which is a Boolean value representing whether or not the control is checked. It also supports one event, ServerChange , which is fired whenever the value of the control changes.

Finally, there are three last HtmlControls on the page that we haven't yet covered. They are shown at the bottom of the Control Tree in the trace output, and appear under the table on the page. They are all HtmlInputControls . These last controls include the HtmlInputHidden , HtmlInputFile , and HtmlInputImage controls.

The HtmlInputHidden control is one of the more useful HtmlControls, because you can use it easily to persist values from page to page with the same techniques employed by most classic ASP applications. However, you should avoid using custom hidden form fields to persist values, because ASP.NET offers several other methods that are usually better. You might store the data as a cookie, or in ViewState , or even in the cache, instead of storing it in its own hidden form field. Consider these alternatives when you are architecting your solutions. The HtmlInputHidden control is very simple, and aside from the properties of the HtmlInputControl , it handles a ServerChange event that is fired whenever its value is changed.

HtmlInputFile Properties

For file uploading, the HtmlInputFile control should be used. It exposes several properties unique to the file uploading process, which are detailed in Table 5.10.

Table 5.10. HtmlInputFile Properties
Property Description
Accept : String Gets or sets a comma-separated list of MIME types that the control will accept as uploads.
MaxLength : Int32 Gets or sets the maximum size of the file to be uploaded, in bytes.
PostedFile : HttpPostedFile Provides access to the file that was uploaded to the control.
Size : Int32 Gets or sets the width of the text box where the file path is entered.

Uploading files was something difficult to manage in classic ASP, requiring a custom component or at the very least some very complicated script code. File uploading with ASP.NET is just as easy as posting any other data to a form ”just one of the many benefits of ASP.NET.

HtmlInputImage Properties

The last HtmlControl on the page is an HtmlInputImage control ( imagebutton1 ). HtmlInputImage controls combine the functions of the HtmlImage and the HtmlInputButton controls, and have the following properties:

HtmlInputImage controls combine the functions of the HtmlImage (with the properties Align : String , Alt : String , Border : Int32 , and Src : String properties) and the HtmlInputButton controls (with the CausesValidation : Boolean property).

That's it; we've looked at every HtmlControl that ships with ASP.NET now, at least briefly . As you've seen, using these controls is very easy, so we're not going to waste time going into any greater depth with these examples. Next we'll take a look at WebControls, which are somewhat more powerful than HtmlControls and are what we will use for the most part throughout the rest of the book in our examples.

I l @ ve RuBoard


Asp. Net. By Example
ASP.NET by Example
ISBN: 0789725622
EAN: 2147483647
Year: 2001
Pages: 154

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