HTML Controls

 

At first sight, HTML server controls look like HTML tags except for the extra runat=server attribute. While it's true that they look the same, the additional runat attribute makes a huge difference. As mentioned, in ASP.NET by simply adding the runat attribute, you can bring to life otherwise dead HTML text. Once transformed into a living instance of a server-side component, the original tag can be configured programmatically using an object-oriented approach. By design, HTML controls expose a set of methods and properties that carefully reflect the HTML syntax. For example, to set the default text of an input form field, you use a property named Value instead of the more expressive Text. The name of the server control is determined by the value of the ID attribute. The following code snippet shows how to define a server-side input tag named lastName:

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

The tag declaration does not include an explicit and static value for the Value attribute, which can be configured programmatically as follows:

void Page_Load(object sender, EventArgs e) {     lastName.Value = "Esposito"; } 

After being processed by the ASP.NET runtime, the preceding declaration generates the following HTML code:

<input name="myName"  type="text" value="Esposito" /> 

Notice that a server-side ID attribute expands to a pair of HTML attributes Name and ID. Be aware that this happens for browser compatibility. In no way does this mean that on the server Name and ID can be used interchangeably to name the server instance of the control. The name of the server control instance is given by ID. If you specify both Name and ID on a server-side tag, the value assigned to Name will be silently overridden.

Generalities of HTML Controls

The .NET Framework provides predefined server controls for commonly used HTML elements such as <form>, <input>, and <select>, as well as for tables, images, and hyperlinks. All the predefined HTML server controls inherit from the same base class the HtmlControl class. In addition, each control then provides its own set of specific properties and its own events.

Controls typically supply properties that allow you to manipulate the HTML attributes programmatically from within server code. HTML controls integrate well with data binding and the ASP.NET state maintenance, and they also provide full support for postback events and client scripting. For example, for a button that gets clicked, you can have some JavaScript code running on the client responding to the onclick event, as well as some code that handles the event on the server if the page posts back as the result of that event.

HTML controls are defined in the System.Web.UI.HtmlControls namespace. Most, but not all, HTML tags have a direct class counterpart in the .NET Framework. HTML elements that don't map to a made-to-measure class are rendered through the HtmlGenericControl class and have attributes set using generic collections rather than direct properties. Generic controls include <iframe>, <hr>, <font>, and <body>. In general, you should bear in mind that every element that can appear in an HTML page can be marked as runat="server" and programmed and styled on the server.

The HtmlControl Base Class

The HtmlControl class inherits from Control and defines the methods, properties, and events common to all HTML controls. Actually, many properties and all methods and events are simply inherited from the base class. Table 4-5 shows the list of properties specific to HTML controls.

Table 4-5: Specific Properties of an HTML Control

Property

Description

Attributes

Gets a collection object representing all the attributes set on the control with the corresponding value

Disabled

Gets or sets a Boolean value, which indicates whether the HTML control is disabled

Style

Gets a collection object representing all CSS properties applied to the control

TagName

Gets the name of the HTML tag behind the control

A disabled HTML server control is visible and always gets generated as HTML code. If the Disabled property is set to true, the disabled HTML attribute is inserted in the HTML output for the control. As mentioned earlier, if the Visible property is set to false, HTML is not generated for the control.

Working with HTML Attributes

Each HTML control features more properties than those listed in Table 4-5. Properties of HTML server controls map to HTML attributes, and the values assigned to the properties are replicated in the HTML output. For controls that don't have an HTML direct counterpart, the Attributes collection is used to set attributes on the resulting HTML tag. This collection can also be used to set properties not mapped by the control's interface and, if needed, to define custom HTML attributes. Any content of the Attributes collection is managed as a string.

Given the following HTML code snippet, let's see how to programmatically set some attributes on the <body> tag:

<script> function Init() {     alert("Hello"); } </script> <script runat=server language="C#"> void Page_Load(object sender, EventArgs e) {    theBody.Attributes["onload"] = "Init()"; } </script> <html> <body runat="server" > </body> </html> 

You bind a JavaScript script to the onload attribute of the <body> tag. The resulting HTML code that the browser displays is as follows:

<script> function Init() {     alert("Hello"); } </script> <html> <body  onload="Init()"> </body> </html> 

The Attributes property is rendered through a special type of class named Attribute-Collection. In spite of the name, the content of the class is not directly enumerable using the for each statement because the IEnumerable interface is not supported. The AttributeCollection class provides ad hoc methods to render attributes of a text writer object and to add and remove elements. Interestingly, if you add an attribute named Style, the class is smart enough to reroute the assigned content to the Style collection.

Hierarchy of HTML Controls

Most HTML controls can be grouped into two main categories container and input controls. A few controls, though, cannot be easily catalogued in either of the two groups. They are HtmlImage, HtmlLink, HtmlMeta, and HtmlTitle, and they are the ASP.NET counterpart of the <img>, <link>, <meta>, and <title> tags. Figure 4-1 shows the tree of HTML controls.

image from book
Figure 4-1: A diagram that groups all HTML controls by looking at their base class. Controls in boldface type require ASP.NET 2.0.

The input controls category includes all possible variations of the <input> tag, from submit buttons to check boxes and from text fields to radio buttons. The container controls category lists anchors, tables, forms, and, in general, all HTML tags that might contain child elements.

HTML Container Controls

The base class for container controls is the HtmlContainerControl class, which descends directly from HtmlControl. The HTML elements addressed by this tag are elements that must have a closing tag that is, forms, selection boxes, and tables, as well as anchors and text areas. Compared to the HtmlControl class, a container control features a couple of additional string properties InnerHtml and InnerText.

Both properties manipulate the reading and writing of literal content found between the opening and closing tags of the element. Note that you cannot get the inner content of a control if the content includes server controls. InnerHtml and InnerText work only in the presence of all literal content. The tag itself is not considered for the output. Unlike InnerText, though, InnerHtml lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, InnerText retrieves and sets the content of the tag as plain text, whereas InnerHtml retrieves and sets the same content but in HTML format.

Table 4-6 lists the HTML container controls defined in ASP.NET.

Table 4-6: HTML Container Controls

Class

Description

HtmlAnchor

Represents an HTML anchor specifically, the <a> tag.

HtmlButton

Represents the HTML <button> tag. The <button> element is defined in the HTML 4.0 specification and supported only in Internet Explorer version 4.0 and later.

HtmlForm

Represents the <form> tag, but can be used only as a container of interactive server controls on a Web page. Cannot really be used to create HTML forms programmable on the server.

HtmlGenericControl

Represents an HTML tag for which the .NET Framework does not provide a direct class. Sample tags include <font>, <hr>, and <iframe>. You program these controls by using the Attributes collection and set attributes indirectly.

HtmlHead

Represents the <head> tag, and allows you to control meta tags, the style sheet, and the page title programmatically. Not available in ASP.NET 1.x.

HtmlSelect

Represents the <select> tag that is, an HTML selection box.

HtmlTable

Represents an HTML table specifically, the <table> tag.

HtmlTableCell

Represents the <td> HTML tag that is, a cell in a table.

HtmlTableRow

Represents the <tr> HTML tag that is, a row in a table.

HtmlTextArea

Represents a multiline text box, and maps the <textarea> HTML tag.

Note that the HtmlButton control is different than HtmlInputButton, which represents the button variation of the <input> tag. The HtmlButton control represents the HTML 4.0_specific <button> tag. We'll say more about buttons in the next section while discussing the Web controls.

Server-side forms play a key role in the economy of ASP.NET applications, as they are the means for implementing postbacks and guaranteeing state maintenance. For this reason, the HtmlForm control is not simply a form element you can program on the server. In particular, the HtmlForm hides the Action property and cannot be used to post content to a page different than the content that generated the HTML for the browser. We will cover HTML forms in great detail in Chapter 5.

Managing Header Information

An instance of the HtmlHead control is automatically created if the page contains a <head> tag marked with the attribute runat=server. Note that this setting is the default when you add a new page to a Visual Studio .NET 2005 Web project, as shown in the following snippet:

<head runat="server">     <title>Untitled Page</title> </head> 

The header of the page is returned through the new Header property of the Page class. The property returns null if the <head> tag is missing or if it is present but lacks the runat attribute.

The HtmlHead control implements the IPageHeader interface, which consists of three collection properties Metadata, LinkedStylesheet, and Stylesheet and a string property Title. The Metadata property is a dictionary that collects all the desired child <meta> tags of the header:

Header.Metadata.Add("CODE-LANGUAGE", "C#"); 

The code results in the following markup:

<meta name="CODE-LANGUAGE" content="C#" /> 

To express other common metadata such as Http-Equiv, you can resort to the newest Html-Meta control, as shown here:

void Page_Init(object sender, EventArgs e) {    HtmlMeta meta = new HtmlMeta();    meta.HttpEquiv = "refresh";    meta.Content = Int32.Parse(Content.Text).ToString();    ((Control)Header).Controls.Add(meta); } 

The preceding code creates a <meta> tag dynamically and adds it to the <head> section of the page during the initialization phase. You can also manipulate an existing <meta> programmatically, as long as it is flagged with the runat attribute.

Tip 

In Internet Explorer only, the <meta> tag can be used to smooth the transition from one page to the next, and also when you move back to a previously visited page. When navigating from page to page in the browser, the current page usually disappears all of a sudden and the new page shows up in its place. By using the following two meta tags, you can make them fade away smoothly:

<meta http-equiv="Page-Enter"       content="progid:DXImageTransform.Microsoft.Fade(duration=.5)" /> <meta http-equiv="Page-Exit"       content="progid:DXImageTransform.Microsoft.Fade(duration=.5)" /> 

Needless to say, the tags can be created and managed programmatically in ASP.NET 2.0.

Note 

To add a <meta> tag programmatically in ASP.NET 1.x, you must resort to a trick. You create the string as a literal control and add it to the Controls collection of the header:

string meta = "<meta http-equiv='refresh' content='3' />"; LiteralControl equiv = new LiteralControl(meta); Header.Controls(equiv); 

Header indicates the server-side <head> tag you're modifying.

To link a style sheet file, you use the following code:

Header.LinkedStyleSheets.Add("MyStyles.css"); 

Alternately, you can resort to the HtmlLink control. The HtmlLink control represents the <link> element. Unlike <a>, the <link> tag can appear only in the <head> section of a document, although it might appear any number of times.

Finally, the HtmlHead control features the Title property, through which you can retrieve and set the title of the page:

Header.Title = "This is the title"; 

Note that this property returns the correct page title only if the <title> tag is correctly placed within the <head> tag. Some browsers, in fact, are quite forgiving on this point and allow developers to define the title outside the header. To manipulate the <title> tag independently from the header, use the HtmlTitle control and mark the <title> tag with the runat attribute.

Note 

In ASP.NET 2.0, the list of HTML elements that enjoy a made-to-measure HTML control grows to include <head>, <title>, <link>, and <meta>. In addition, some special configurations of the <input> tag have a corresponding HTML control. These corresponding HTML controls are submit buttons, reset buttons, and password fields.

Navigating to a URL

The HtmlAnchor class is the programmatic way of accessing and configuring the <a> tag. With respect to the other container controls, the HtmlAnchor class provides a few extra properties such as HRef, Name, Target, and Title. The HRef property sets the target of the hyperlink and can be used to navigate to the specified location. The Name property names a section in the ASP.NET page that can be reached from anywhere on the same page through #-prefixed HRefs. The following code demonstrates a bookmarked anchor named MoreInfo:

<a name="MoreInfo" /> 

This anchor can be reached using the following hyperlink:

<a href="#MoreInfo">Get More Info</a> 

The Target property identifies the target window or the frame where the linked URL will be loaded. Common values for Target are _self, _top, _blank, and _parent, as well as any other name that refers to a page-specific frame. Although the feature is mostly browser-dependent, you should always consider these special names as lowercase. Finally, the Title property contains the text that virtually all browsers display as a ToolTip when the mouse hovers over the anchor's area.

Handling Events on the Server

In addition to being used for navigating to a different page, the anchor control as well as the HtmlButton control can be used to post back the page. Key to this behavior is the ServerClick event, which lets you define the name of the method that will handle, on the server, the event generated when the user clicks the control. The following code demonstrates an anchor in which the click event is handled on both the client and server:

<a runat=server onclick="Run()" onserverclick="DoSomething">Click</a> 

The onclick attribute defines the client-side event handler written using JavaScript; the onserverclick attribute refers to the server-side code that will run after the page posts back. Of course, if both event handlers are specified, the client-side handler executes first before the post back occurs.

The HtmlSelect Control

The HtmlSelect control represents a list of options from which you choose one or more. You control the appearance and behavior of the control by setting the Size and Multiple properties. The Size property specifies the number of rows to be displayed by the control, whereas the Multiple property indicates whether more than one item can be selected in the control. Internal items are grouped in the Items collection, and each element is represented by a ListItem object. Interestingly, the ListItem class is not defined in the HtmlControls namespace but lives instead in the WebControls namespace. To specify the text for each selectable item, you can either set the Text property of the ListItem or simply define a series of <option> tags within the opening and closing tags of the <select> element.

By default, the HtmlSelect control shows up as a drop-down list. However, if multiple selections are allowed or the height is set to more than one row, the control is displayed as a list box. The index of the selected item in a single-selection control is returned through the SelectedIndex property. If the multiple selection is enabled, you just loop through the Items collection and check the Selected property on individual list items.

The HtmlSelect control supports data binding through additional properties. The DataSource property lets you set the data source, which can be any .NET object that implements the IEnumerable interface. If the data source contains multiple bindable tables (for example, a DataSet object), by using the DataMember property you can choose a particular one. Finally, the DataTextField and DataValueField properties are used to bind the list item's Text and Value properties to columns in the data source. (We'll cover data binding in Chapter 9.)

HTML Tables

In ASP.NET, HTML tables provide a minimum set of functions when rendered using the HtmlTable control. In most cases, you don't need to use server-side tables because you typically rely on richer list and grid controls to do the job of displaying tables or records. So you resort to tables when you need to define a fixed layout for graphical elements of the page, but this is not a feature that requires a server-side table.

Server-side tables are not as powerful as pure HTML tables which are created by using the <table> tag. The main limitation is that the HtmlTable class does not support HTML elements such as <caption>, <col>, <colgroup>, <tbody>, <thead>, and <tfoot>. If you use these elements in your ASP.NET code, no run-time exception or compile error is ever thrown. Nevertheless, those elements are silently removed from the HTML code being generated. For example, let's consider the following code:

<table runat="server">     <thead><th>Name</th><th>Last Name</th></thead>     <tr><td>Joe</td><td>Users</td></tr>     <tr><td>Bob</td><td>Whosthisguy</td></tr> </table> 

As you can see in the following code, the HTML output that is generated by the preceding example does not include the <thead> element:

<table>     <tr><td>Joe</td><td>Users</td></tr>     <tr><td>Bob</td><td>Whosthisguy</td></tr> </table> 

By design, an HtmlTable control can have only children of the HtmlTableRow class. Any attempt to progrpammatically add other table elements, such as a <thead> or a <tfoot>, will generate an exception.

The behavior of HtmlTable doesn't change in ASP.NET 2.0. However, the newer version of ASP.NET provides a richer server-side support for tables through the Table control the HtmlTable counterpart in the WebControls namespace. In particular, you can associate each TableRow object with a particular section, be it header, body, or footer. When the Table control renders out to HTML, it checks the section of each row and inserts <tbody>, <thead>, and <tfoot> as appropriate.

The HtmlTextArea Control

The HtmlTextArea control corresponds to the <textarea> HTML element and allows you to programmatically create and configure a multiline text box. The HtmlTextArea class provides the Rows and Cols properties to control the number of rows and columns of the text box. The Value property can be used to assign some text to display in the control area.

The HtmlTextArea class also provides a ServerChange event that fires during a postback and allows you to validate on the server the data contained in the control. Note that the HtmlTextArea control does not fire the event itself and does not directly cause the page to post back. Rather, when the page posts back in response to a click on a link or submit button, the HtmlTextArea control intervenes in the server-side chain of events and gives the programmer a chance to run some code if the internal content of the control is changed between two successive postbacks.

All ASP.NET controls that, like HtmlTextArea, implement the IPostBackDataHandler interface can invoke user-defined code when the control's internal state changes. As discussed in Chapter 3, controls can fire custom events by overriding the RaisePostDataChangedEvent method on the aforementioned interface. The following pseudocode shows what happens in the method's implementation of HtmlTextArea:

void System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() {     this.OnServerChange(EventArgs.Empty); } 

Finally, note that the control raises the event only if the state has changed between two successive posts. To determine whether that has happened, the control needs to track the content it had the time before. This value can be stored only in the view state. Of course, the ServerChange event won't fire if you disable the view state for the host page or the control.

HTML Input Controls

In HTML, the <input> element has several variations and can be used to provide a submit button as well as a check box or text box. In ASP.NET, each possible instance of the <input> element is mapped to a specific class. All input classes derive from the HtmlInputControl class. HtmlInputControl is the abstract class that defines the common programming interface for all input controls. The class inherits from HtmlControl and simply adds three custom properties Name, Type, and Value to the inherited interface.

The Name property returns the name assigned to the control. In ASP.NET, this property is peculiar because, although it's marked as read/write, it actually works as a read-only property. The get accessor returns the control's UniqueID property, while the set accessor is just void. As a result, whatever value you assign to the property, either programmatically or declaratively, is just ignored and no exception or compile error is ever thrown.

The Type property mirrors the type attribute of the HTML input elements. The property is read-only. Finally, the Value property is read/write and represents the content of the input field.

Table 4-7 lists the HTML input controls defined in ASP.NET.

Table 4-7: HTML Input Controls

Class

Description

HtmlInputButton

Represents the various flavors of a command button supported by HTML. Feasible values for the Type attribute are button, submit, and reset.

HtmlInputCheckBox

Represents an HTML check box that is, the <input> tag with a type equal to checkbox.

HtmlInputFile

Represents the file uploader that is, the <input> tag with a type equal to file.

HtmlInputHidden

Represents a hidden buffer of text data that is, the <input> tag with a type equal to hidden.

HtmlInputImage

Represents a graphic button that is, the <input> tag with a type equal to image. Note that this tag is supported by all browsers.

HtmlInputPassword

Represents a protected text field that is, the <input> tag with a type of password. Not available in ASP.NET 1.x.

HtmlInputRadioButton

Represents a radio button that is, the <input> tag with a type equal to radio.

HtmlInputReset

Represents a reset command button. Not available in ASP.NET 1.x.

HtmlInputSubmit

Represents a reset command button. Not available in ASP.NET 1.x.

HtmlInputText

Represents a text field that is, the <input> tag with a type of either password or text.

The hidden and text input controls are nearly identical, and the contents of both are posted back. Essentially, they differ only in that hidden fields are not displayed and, subsequently, they don't provide some UI-related properties such as MaxLength and Size.

Command Buttons

The HtmlInputButton class is the most flexible button class in the .NET Framework. It differs from the HtmlButton class in that it renders through the <input> tag rather than the Internet Explorer-specific <button> tag. This fact ensures much wider support for the control from browsers.

The HTML input button controls support the ServerClick event, which allows you to set the code to run on the server after the button is clicked. Note that if you set the button type to Button and the ServerClick event handler is specified, the control automatically adds the postback script code to the onclick HTML attribute. In this way, any click causes the page to post back and the code to execute. Let's consider the following ASP.NET code:

<input runat="server" type="button"  value="Click"     onserverclick="buttonClicked" /> 

The corresponding HTML code is as follows:

<input language="javascript" onclick="__doPostBack('btn','')" name="btn"     type="button" value="Click" /> 

The client-side __doPostBack script function is the standard piece of code generated by ASP.NET to implement the postback. If the button type is set to Submit that is, a value that would always cause a postback no client-side script code is generated and the onclick attribute is not set.

In ASP.NET 2.0, more specific controls have been added to render submit and reset buttons: HtmlInputSubmit and HtmlInputReset.

Note 

The HtmlInputImage control supports a nearly identical pattern for handling server-side events and validation. The HtmlInputImage control features a few more properties specific to the image it shows. In particular, you can set the alternate text for the image, the border, and the alignment with respect to the rest of the page. The ServerClick event handler has a slightly different form and looks like the following:

void ImageClickEventHandler(object sender, ImageClickEventArgs e); 

When an image button is clicked, the coordinates of the click are determined by using the X and Y properties of the ImageClickEventArgs data structure.

Controlling Validation

The HtmlInputButton class, as well as the HtmlButton class, support a Boolean property named CausesValidation. The property indicates whether the content of the input fields should be validated when the button is clicked. By default, the property is set to true, meaning the validation always takes place. We'll examine data validation later in the chapter. For now, suffice it to say that you can programmatically enable or disable the validation step by using the CausesValidation property.

Typically, you might want to disable validation if the button that has been clicked doesn't perform a concrete operation but simply clears the user interface or cancels an ongoing operation. By design, in fact, server-side page validation takes place just before the ServerClick event handler is executed. Setting the CausesValidation property to false is the only means you have to prevent an unnecessary validation.

Detecting State Changes of Controls

Earlier in this chapter, while discussing the features of the HtmlTextArea control, we ran into the ServerChange event and described it as the mechanism to detect and validate changes in the control's state between two successive postbacks. The ServerChange event is not an exclusive feature of the HtmlTextArea control but is also supported by other input controls such as HtmlInputCheckBox, HtmlInputRadioButton, HtmlInputHidden, and HtmlInputText. Let's look at an example in which we use the ServerChange event to detect which elements have been checked since last time the control was processed on the server.

We build a page with a list of check boxes and a button to let the user post back to the server when finished. Notice, in fact, that neither the HtmlInputCheckBox control nor any other input control except buttons posts back to the server when clicked. For this reason, you must provide another control on the Web page that supports posting to the server for example, an HtmlButton or an HtmlInputButton control. The following code implements the page shown in Figure 4-2:

<%@ Page Language="C#" %> <html> <script runat="server"> public void DetectChange(object sender, EventArgs e) {     HtmlInputCheckBox cb = (HtmlInputCheckBox) sender;     Response.Write("Control <b>" + cb.UniqueID + "</b> changed<br>"); } </script> <body> <form runat="server">     <input runat="server" type="checkbox"          OnServerChange="DetectChange">One<br>     <input runat="server" type="checkbox"          OnServerChange="DetectChange">Two<br>     <input runat="server" type="checkbox"          OnServerChange="DetectChange">Three<br>     <input runat="server" type="submit" value="Submit" /> </form> </body> </html> 

image from book
Figure 4-2: The ServerChange event fires only if the status of the control has changed since the last time the control was processed on the server.

The ServerChange event is fired only if the state of the control results changed after two post-backs. To get the first screen shot, you check the element and then submit. Next, if you submit again without checking or unchecking anything, you get the second screen shot.

As mentioned in Chapter 3, by implementing the IPostBackDataHandler interface, each server control gets a chance to update its current state with data posted by the client. I cover this interface in detail in Programming Microsoft ASP.NET 2.0 Applications: Advanced Topics.

Uploading Files

The HtmlInputFile control is the HTML tool for uploading files from a browser to the Web server. Note that file upload requires Internet Explorer version 3.0 or newer. To take advantage of the HtmlInputFile control, you should first ensure that the server form's Enctype property is set to multipart/form-data. Note, though, that in ASP.NET 2.0, the proper EncType is automatically set, care of the HtmlInputFile control, before the control's markup is rendered:

<form runat="server" enctype="multipart/form-data">     <input runat="server" type="file"  >     <input runat="server" type="submit" value="Upload..." /> </form> 

The way in which the HtmlInputFile control is rendered to HTML is browser-specific, but it normally consists of a text box and a Browse button. The user selects a file from the local machine and then clicks the button to submit the page to the server. When this occurs, the browser uploads the selected file to the server, as shown in Figure 4-3.

image from book
Figure 4-3: A new file has been uploaded to the Web server and copied to the destination folder.

Note 

Prior to ASP.NET, a server-side process the posting acceptor was required to run in the background to handle multipart/form-data submissions. In ASP.NET the role of the posting acceptor is no longer necessary, as it is carried out by the ASP.NET runtime itself.

On the server, the file is parked in an object of type HttpPostedFile and stays there until explicitly processed for example, saved to disk or to a database. The HttpPostedFile object provides properties and methods to get information on an individual file and to read and save the file. The following code shows how to save a posted file to a particular folder to disk:

<%@ Page language="C#" %> <%@ Import Namespace="System.IO" %> <script runat="server">     void UploadButton_Click(object sender, EventArgs e)     {         // *** ASSUME THE PATH EXISTS ***         string savePath = @"c:\temp\Pictures\";         if (!Directory.Exists(savePath)) {             string msg = "<h1>The upload path doesn't exist: {0}</h1>";             Response.Write(String.Format(msg, savePath));             Response.End();         }         // Verify that a file has been posted         if (FileUpload1.PostedFile != null)         {             // Save the uploaded file to the specified path             string fileName = Path.GetFileName(FileUpload1.Value);             savePath += fileName;             FileUpload1.PostedFile.SaveAs(savePath);             // Notify the user of the name the file was saved under.             UploadStatus.InnerText = "File saved as: " + savePath;         }         else         {             // Notify the user that a file was not uploaded.             UploadStatus.InnerText = "No file specified.";         }     } </script> <html> <head runat="server">     <title>Pro ASP.NET (Ch04)</title> </head> <body>     <form runat="server">       <h3>Select a picture to upload:</h3>         <hr />         <b>Picture to upload</b><br />         <input type="file"  runat="server" />         <br><br>         <input runat="server"  type="submit"              value="Upload" onserverclick="UploadButton_Click" />         <hr />         <span runat="server"  />      </form> </body> </html> 

You can also use the InputStream property of the HttpPostedFile object to read the posted data before persisting or processing. The HttpInputFile control also allows you to restrict the file types that can be uploaded to the server. You do this by setting the Accept property with a comma-separated list of MIME types.

Caution 

When you use the SaveAs method, you should be sure to specify the full path to the output file. If a relative path is provided, ASP.NET attempts to place the file in the system directory. This practice can result in an access denied error. Furthermore, be sure to provide write permission for the account used by ASP.NET for the directory where you want to store the file.

ASP.NET exercises some control on the amount of data being uploaded. The maxRequestLength attribute in the <httpRuntime> section of the configuration file sets the maximum allowable file size. An error is generated in the browser when the file exceeds the specified size 4 MB by default. Uploading large files might also generate another run-time error as a result of an excessive consumption of system memory.

The HtmlImage Control

The HtmlImage class is the ASP.NET counterpart of the <img> tag. You can use it to configure on the server the display of an image. Possible parameters you can set are the size of the image, the border, and the alternate text. An instance of HtmlImage is created only when the runat attribute is added to the <img> tag. If you simply need to display an image within a page, and the image is not dynamically determined or configured, there is no need to resort to the HtmlImage control, which would add unnecessary overhead to the page.

The following code snippet shows how to configure a server-side <img> tag called to display an image whose name is determined based on run-time conditions:

theImg.Width = 100; theImg.Height = 100; theImg.Src = GetImageUrl(Request); 

The HtmlImage control should be used to programmatically manipulate the image to change the source file, the width and height, or the alignment of the image relative to other page elements. The majority of properties of the HtmlImage control are implemented as strings, including Src the URL of the image and Align. Feasible values of Align are only a small set of words such as left, right, top, and so forth. These words would have been more appropriately grouped in a custom enumerated type, thus providing for a strongly typed programming model. If you think so, too, you just got the gist of the difference between HTML and Web server controls! HTML controls just mirror HTML tags; Web controls attempt to provide a more consistent and effective programming interface by exploiting the characteristics of the .NET Framework.

image from book
Literal Controls

Literal controls are a special type of server control that ASP.NET creates and uses when-ever it encounters plain text that doesn't require server-side processing. In general, everything that appears in the context of an ASP.NET page is treated like a control. If a tag includes the runat="server" attribute, ASP.NET creates an instance of a specific class; otherwise, if no runat attribute has been specified, the text is compiled into a LiteralControl object. Literal controls are simple text holders that are added to and removed from pages using the same programming interface defined for other server controls.

Note that a literal control is created for each sequence of characters placed between two successive server controls, including carriage returns. Using a new line to separate distinct server controls and increase code readability actually affects the number of server controls being created to serve the page. Writing the page as a single string without carriage returns produces the smallest number of server controls.

 


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