JavaScript Editor Javascript validator     Javascripts

Main Page


Previous Section Next Section

4.1 HTML Server Controls

Normal HTML controls such as <h1>, <a>, and <input> are not processed by the server, but are sent directly to the browser for display. Standard HTML controls can be exposed to the server and made available for server-side processing by turning them into HTML server controls. Server-side processing allows for data binding, programmatic response to events, and the ability to use a fully featured and compiled coding language rather than a scripting language.

To convert an HTML control to an HTML server control, simply add the attribute runat="server". In addition, you will probably want to add an id attribute, so that contents of the control can be accessed and controlled programmatically. For example, start with a simple input control:

<input type="text" size="40">

You can convert it to an HTML server control by adding the id and runat attributes, as follows:

<input type="text" id="BookTitle" size="40" runat="server">

There are several benefits to converting an HTML control to an HTML server control:

  • Once a control is converted to a server control, it can be referred to in code. For example, in Example 4-1 and Example 4-2 you can read or set the value of the text box by referring to lblBookName.Value or txtBookName.Value.

  • Server controls retain state during round trips to the server (more on this in Chapter 6).

  • Server controls generate events, which your code can then handle.

  • Server controls are aware of the client browser level and generate HTML appropriate to the target browser.

Example 4-1 and Example 4-2 demonstrate the use of HTML server controls in C# and VB.NET, respectively. In these listings, a text box is used to prompt the user to enter a book name. When the Button control is clicked, it fires an event that fills a second text box with the contents of the first text box and also changes its size.

Example 4-1. Code listing for csHTMLServerControls.aspx
<%@ Page Language="C#" %>
<html>

<script runat="server">
   void btnBookName_Click(Object Source, EventArgs E)
   {
      lblBookName.Value = txtBookName.Value;
      lblBookName.Size = 80;
   }
</script>

   <body>
   <form runat=server>

      <h1>HTML Server Controls</h1>

      <br/>
      <h2>The date and time is <% =DateTime.Now.ToString(  ) %>.</h2>

      <br/>

      <h2>HTML Server Control</h2>
      Book Name:&nbsp;&nbsp;&nbsp;
      <input type="text" 
         id="txtBookName" 
         size="40" 
         value="Enter book name."
         runat="server" />

      <br/>
      <br/>
      <br/>

      <input type="submit" 
         id="btnBookName" 
         value="Book Name" 
         onServerClick="btnBookName_Click" 
         runat="server" />
      <br/>
      <br/>
      <input type="text" id="lblBookName" size="40" runat="server" />

   </form>
   </body>
</html>
Example 4-2. Code listing for vbHTMLServerControls.aspx
<%@ Page Language="VB" %>
<html>

<script runat="server">
   Sub btnBookName_Click(ByVal Sender as Object, _
                         ByVal e as EventArgs)
   
      lblBookName.Value = txtBookName.Value
      lblBookName.Size = 80
   End Sub
</script>

   <body>
   <form runat=server>

      <h1>HTML Server Controls</h1>

      <br/>
      <h2>The date and time is <% =DateTime.Now(  ) %>.</h2>

      <br/>

      <h2>HTML Server Control</h2>
      Book Name:&nbsp;&nbsp;&nbsp;
      <input type=text 
         id="txtBookName" 
         size="40" 
         value="Enter book name."
         runat="server" />

      <br/>
      <br/>
      <br/>

      <input type="submit" 
         id="btnBookName" 
         value="Book Name" 
         onServerClick="btnBookName_Click" 
         runat="server" />

      <br/>
      <br/>
      <input type="text" id="lblBookName" size="40" runat="server"/>

   </form>
   </body>
</html>

Consider the very first line of code in both listings:

<%@ Page Language="C#" %>
<%@ Page Language="VB" %>

This is a page directive, which tells the compiler that any script found in this page is written using the C# or VB language, respectively. Immediately following the opening <HTML> tag in Example 4-1 and Example 4-2 is a script block, written in C# or VB.NET, respectively, as indicated by the page directive. It contains a routine called btnBookName_Click, which is the event handler for the Click event of the btnBookName button. This method takes two parameters and returns nothing (as indicated by the void keyword in C# and the Sub keyword in VB.NET). These parameters are typical for all event handler methods in ASP.NET, as discussed in Chapter 3. In C#, the parameter list is of the form:

(Object Source, EventArgs E)

In VB.NET, the parameter list is of the form:

(ByVal Sender as Object, ByVal e as EventArgs)

Note that within the body of the routine, the HTML server controls are referred to by their id attribute, for example lblBookName and txtBookName.

The Submit button is shown here:

<input type="submit"

This is prototypical of converting HTML controls to server controls. It has an id attribute and the runat attribute:

id="btnBookName"
runat="server"

Rather than the traditional onClick attribute used in conventional HTML or ASP pages, the Submit button has an onServerClick attribute, telling the server what function to call when the Click event occurs:

onServerClick="btnBookName_Click"

If you want the control to handle the event on the client side, you should use the onClick attribute. In this case, you must provide client-side scripting to handle the event. You cannot have both an onClick and onServerClick attribute for the same control.

Figure 4-1 shows the page that results from running the code in either Example 4-1 or Example 4-2, filling in a book name, and clicking the Book Name button.

Figure 4-1. Output from Example 4-1 or Example 4-2
figs/pan2_0401.gif

Example 4-3 and Example 4-4 show both input controls and HTML server container controls in C# and VB.NET, respectively, and demonstrate the use of the InnerHtml property.

Example 4-3. Input and container HTML server controls using C#, csHTMLServerControls2.aspx
<%@ Page Language="C#" %>

<script runat="server">
   void Page_Load(Object Source, EventArgs E)
   {
      string strHtml = "";
      strHtml += txtName.Value + "<br/>";
      strHtml += txtStreet.Value + "<br/>";
      strHtml += txtCity.Value + ", " + txtState.Value;
      tdInnerHtml.InnerHtml = strHtml;
   }
</script>

<html>
   <body>
   <form runat="server">

      <h1>HTML Server Controls</h1>
      <h2>InnerHTML</h2>

      <table>
         <tr>
            <td>Name:</td>
            <td>
                <input type="text"
                    id="txtName"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>Street:</td>
            <td>
                <input type="text"
                    id="txtStreet"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>City:</td>
            <td>
                <input type="text"
                    id="txtCity"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>State:</td>
            <td>
                <input type="text"
                    id="txtState"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td></td>
            <td id="tdInnerHtml" runat="server" />
         </tr>
      </table>

      <input type="submit" value="Do It!">

    </form>
   </body>
</html>
Example 4-4. Input and container HTML server controls using VB.NET, vbHTMLServerControls2.aspx
<%@ Page Language="VB" %>

<script runat="server">
   sub Page_Load(ByVal Sender as Object, _
                 ByVal e as EventArgs)
      dim strHtml as string
      strHtml = txtName.Value & "<br/>"
      strHtml = strHtml & txtStreet.Value & "<br/>"
      strHtml = strHtml & txtCity.Value & ", " & txtState.Value
      tdInnerHtml.InnerHtml = strHtml
   end sub
</script>

<html>
   <body>
   <form runat="server">

      <h1>HTML Server Controls</h1>
      <h2>InnerHTML</h2>

      <table>
         <tr>
            <td>Name:</td>
            <td>
                <input type="text"
                    id="txtName"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>Street:</td>
            <td>
                <input type="text"
                    id="txtStreet"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>City:</td>
            <td>
                <input type="text"
                    id="txtCity"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td>State:</td>
            <td>
                <input type="text"
                    id="txtState"
                     runat="server"/>
            </td>
         </tr>
         <tr>
            <td></td>
            <td id="tdInnerHtml" runat="server" />
         </tr>
      </table>

      <input type="submit" value="Do It!">

    </form>
   </body>
</html>

In Example 4-3 and Example 4-4, the two types of input controls are text fields and a button. Both happen to use the <input> HTML tag, although as you can see in Table 4-1, there are other input controls that do not use those tags.

Table 4-1. HTML tags and their categories

HTML tag

Category

HTML server control name

Description

<input>

Input

HtmlInputButton HtmlInputCheckBox HtmlInputFile HtmlInputHidden HtmlInputImage HtmlInputRadioButton HtmlInputText

<input type=button | submit | reset> <input type=checkbox> <input type=file> <input type=hidden> <input type=image> <input type=radio> <input type=text | password>

<img>

Input

HtmlImage

Image

<textarea>

Input

HtmlTextArea

Multiline text entry

<a>

Container

HtmlAnchor

Anchor

<button>

Container

HtmlButton

Customizable output format, usable with IE 4.0 and above browsers

<form>

Container

HtmlForm

Maximum of one HtmlForm control per page; default method is POST

<table>

Container

HtmlTable

Table, which can contain rows, which can contain cells

<td> <th>

Container

HtmlTableCell

Table cell Table header cell

<tr>

Container

HtmlTableRow

Table row

<select>

Container

HtmlSelect

Pull-down menu of choices

 

Container

HtmlGenericControl

Any HTML control not listed here

The table, which is a container control, is used in these examples primarily as a means of controlling the layout of the other controls on the page. It has not been converted to an HTML server control, since it does not have the runat="server" attribute. One of the cells, however, has been converted for server-side processing by the inclusion of that attribute. In addition, that cell has an id attribute so that it can be referred to programmatically in the Page_Load routine.

Looking at the Page_Load routine, which is executed every time the page is posted, (that is, every time the Do It! button is clicked), an HTML string is constructed containing the values of the input text fields, interspersed with some HTML to control line breaks. This string is then assigned to the InnerHtml property of the table cell with the tdInnerHtml id attribute:

tdInnerHtml.InnerHtml = strHtml

If the InnerText property is used instead of the InnerHtml property, then the resulting page would display the actual < and > symbols. As written, however, the resulting page will look something like Figure 4-2, after values are entered in the text fields and the button is clicked.

Figure 4-2. Output from Example 4-3 or 4-4
figs/pan2_0402.gif

Table 4-1 lists HTML tags and the category to which they belong.

You never actually use the name of HTML server control shown in Table 4-1 in any of your code. What goes in your HTML code is the HTML tag with the addition of the runat="server" attribute and usually with the addition of an id attribute.

Actually, any HTML control can be converted to server-side processing with the addition of the runat="server" attribute. If the control is not listed in Table 4-1, then it will be treated as an HtmlGenericControl. As with any other container control, this allows programmatic access to the control's inner HTML.

All the HTML server controls derive from the System.Web.UI.Control class and are contained in the System.Web.UI.HTMLControls namespace. Figure 4-3 shows the HTML server control hierarchy.

Figure 4-3. The HTML server control object hierarchy
figs/pan2_0403.gif

Well-Formed HTML

Well-formed HTML (sometimes called XHTML) conforms to the rules for XML. Many web browsers are very forgiving, and ill-formed HTML will work fine, but the world is moving toward a stricter syntax in order to increase the robustness of the Web. Well-formed code has a huge benefit for authoring tools and is worthwhile when hand coding as well, since it decreases confusion and ambiguity.

Among the rules of well-formed HTML are these:

Close all tags

Several HTML tags, such as <p>, <tr>, and <td>, are routinely left unclosed. In well-formed HTML, there will always be a closing tag, such as </td>. Many tags, such as <br>, <hr>, <input>, and <img>, can be made self-closing by putting the closing forward slash within the tag itself. This makes it well-formed. For example:

<input type="submit"
id="btnBookName"
value="Book Name"
onServerClick="btnBookName_Click"
runat="server" />
No overlapping tags

Some browsers are tolerant of overlapping tags, but well-formed HTML requires that tags do not overlap. For example, consider the overlapping tags in the following line of HTML:

<b>This is <i>the year</b>for the Red Sox.</i>

This can instead be expressed as:

<b>This is</b> <i><b>the year</b>for the Red Sox.</i>
Case-sensitivity

Like all HTML and ASP pages, ASP.NET is generally not case-sensitive. The one glaring exception is that C#, when it is used, is always case-sensitive. That said, it should be noted that script components are actually XML files, and as such should follow XML Version 1.0 conventions. According to these conventions, element types and attributes are case-sensitive. This will usually only matter if you use an XML editing tool to work with the script components or if you are creating an XML file (such as an advertisement file for use with the AdRotator control, described in Chapter 5). However, it is good practice to follow the XML guidelines. Element types and attributes are usually lowercase, except multipart names (such as onServerClick), which use camel notation, with initial lowercase. For other HTML tags, being well-formed requires that start and end tags have matching case. This book will generally use lowercase for all HTML tags.

Quotation marks

In well-formed HTML, all attributes are enclosed in quotation marks.

Single root

The top-level element in a page must be <html>. Remember to close it at the end with </html>.

Reserved characters

There are only five built-in character entities in XML. They are:

&lt;     <
&gt;     >
&amp;      &
&quot;      "
&apos;      '

If any of these characters is used in script, then it must be "escaped" by using the above character entity, or by enclosing the entire script block in a CDATA section. (CDATA is an XML type.)

HTML controls are divided into two categories: input and container. HTML input controls do not require a closing tag (although to be well-formed, they should be made self-closing with a trailing /) and have Name, Value, and Type attributes, which may be accessed and controlled programmatically.

HTML container controls are required to have either a trailing / or a closing tag. They do not have Name, Value, or Type attributes. Instead, the content found between opening and closing tags may be accessed programmatically using the InnerHtml or InnerText property. The difference between these two properties is that InnerText provides automatic HTML encoding and decoding of special characters, such as < or >. If the InnerHtml property is used, these characters are interpreted as being part of the HTML and will not display in the final output.

    Previous Section Next Section


    JavaScript Editor Javascript validator     Javascripts 
    Bitcoin Dice - Crypto Casino



    ©