Before getting into developing your favorite Hello, World! application in ASP1NET, it's important that you become familiar with the underlying structure of ASP1NET1 This section describes some of the most important classes packaged in the System1Web1UI namespace in the ASP1NET framework1
The System1Web1UI namespace defines classes and interfaces used in constructing and rendering elements on a Web Form1 The most important class in the System1Web1UI is the Control class, which defines properties, methods, and events that are common in all server controls in the Web Forms framework1 Another important class in this namespace is Page, which is a derivative of the Control class1 All ASP1NET web pages are instances of derivatives of the Page class1 To have an extensible framework, the System1Web1UI namespace also includes the UserControl class, which is similar to the Page class except that it is used as the base class for user controls1 We will make use of the UserControl and Page classes in Section 715 and Section 71514 sections later in this chapter1
The Control class is the root of all controls1 For example, a text box is a control; a button or a combo box is also a control1 The Control class basically encapsulates common functionalities and properties of all user-interface widgets1 As you get deeper into ASP1NET development, everything you see is a Control derivative of some sort1
The Control class has the following important properties: Controls, ID, ClientID, Parent, EnableViewState, Visible, Context, and ViewState1 We will go over each of these properties briefly to show you what the Control class is made up of and how deriving from Control class would create a model that is consistent and easy to work with1
The Controls property represents the children of the control instance; the Parent property defines the parent of the control1 These properties enable a hierarchy of controls on a web page1 The ID property allows the control to be accessed programmatically by just using the ID and the dot notation to get to the object's properties and methods (i1e1, MyObjectId1propertyname)1 While the ID property allows us to program the control on the server side, ClientID allows us to setup client-side script to access the control on the client side1 More information on using ClientID will be shown later in this chapter1
The EnableViewState flag indicates whether the control will maintain its view state, as well as all view states of its child controls1 If this flag is set to true, the control will remember its previous view state when the page posts back to itself1[1] For example, if EnableViewState is set to true, the user's previous selection or form-field data are preserved automatically when the user performs some operation that requires a postback1 When the page is sent back to the browser, the user can just continue filling in the form as if he never left it1 This is how all derivatives of the Control class maintain their states between requests and free ASP developers from having to simulate view-state behavior with hidden form fields1
[1] Postback is the condition when an ASP page posts the data back to itself for processing1 In conventional ASP programming, the states of the fields in the form have to be managed manually1 In ASP1NET, we can have these field states managed automatically with a simple EnableViewState flag1
The Context property enables us to get to information about the current HTTP request, such as the Application, Server, Session, Request, and Response objects1 ASP developers should be familiar with these intrinsic objects1 You will likely use the Context property when you are processing the web page's Load event to get to application- or session-level variables and request parameters to set up your page1 Through the Context property, you can also get other information, such as cached resources, including database connection for performance improvement; the trace property for debugging purposes; and the user property for security validation1
The ViewState property is an instance of the StateBag class, which is used to store name/value pairs of information that can be made accessible across multiple requests for the same web page1 These name/value pairs are instances of the StateItem class1 ViewState allows ASP1NET controls to maintain their own state across multiple client roundtrips; it is implemented as a hidden form field on the page1 If you've attempted to maintain state for your form in ASP development, you will appreciate this because it is now automatically done for you1
The list of methods for the Control class is much longer than what we've covered in this section; however, this short list is probably all you need to know to get started with the Control class:
Binds the control to a data source1 This method is used in conjunction with the data-binding expression syntax on the Web Form1 When this method is called, all data-binding tags, <%# %>, are re-evaluated so that the new data is bound to the appropriate tag location1 Also, any controls that have their DataSource property set, retrieve the data from the DataSource and fill themselves1
Called before any compositional custom control is rendered1 A compositional custom control is similar to a user control1 Both of them are composed of other controls to create more complex controls1 You would not employ this method simply to use the control1 When developing custom controls, this method can be overridden so that custom control developers can create and layout child controls prior to rendering the controls, whether for the first time or for postbacks1
Similar to the CreateChildControls, primarily used to develop custom controls1 Control developers override this method to render the control content through the provided HtmlTextWriter parameter1
We will revisit the Render and CreateChildControls methods when we show you how to create custom controls in "Customer Server Controls" later in this chapter1
Save and reload the state for the control1 Server controls maintain their state between requests via these methods1
As mentioned earlier, the Page class is actually a derivative[2] of the Control class1 This means it inherits all properties, methods, and events exposed by the Control class1 In addition to the inherited things, the Page class defines more specific properties, methods, and events for a web page in the ASP1NET framework1
[2] The Page class derives from TemplateControl, which derives from the Control class1
If you've done ASP development, you already know that Application, Request, Response, Server, and Session are intrinsic objects that you can access while scripting your ASP page1 With ASP1NET, these objects are actually properties of the Page class1 In addition to these familiar objects, the Page class also exposes other properties such as Cache, ErrorPage, IsPostBack, IsValid, Trace, and Validators1
This list is not complete; however, it includes some of the more important features that we want to introduce:
Points to a Cache object of the Context for the current page1 Here, resources such as DataSet with information retrieved from a database are stored for reuse while the cache item is not yet expired1
Specifies the page to display when an error occurs1 You can also specify the error page by using theSection 7141
Indicates whether the page request is an original request or a postback, since the interaction between the user and the server controls requires a postback to the current page1 If IsPostBack is true, you should not redo all your page initialization to improve performance1
Groups together server controls that can validate themselves inside the Validators property of the Page1 (In ASP1NET, a web page usually consists of a number of server controls1) This is so that when the Page needs to validate itself, it can delegate the validation to all of these controls and then set the IsValid property to the appropriate value1
References a TraceContext object, through which you can issue warning or error messages1 Tracing can be switched on or off at any time from the web1config setting1 web1config is an XML-based text file that stores the runtime configuration for an ASP1NET application1 Changes to this file take effect immediately1 The main configuration file is at the root of your web application; however, you can have a configuration file for each subdirectory in your web application1 The closest configuration file overrides the settings of distant configuration files1 Being able to switch off tracing in a configuration file like this is much better than doing so manually in ASP development, where you must go through all ASP files to remove all instances of Response1Write debugging messages when you are ready to deploy your application1
Loads server controls from a file into the page programmatically1 This is especially for user controls in ascx files1 For ordinary server controls, they can be instantiated directly and added to the page's Controls collection1 You can also have static server control declared on the page using the server-side object syntax as described in Section 714 later in this chapter1
Maps a virtual path to a physical path for file I/O1 This should be familiar to ASP developers1
Works with the Server Validation Controls on the page to validate data on the page1 If any of the server controls fail to validate, this method returns false, and the failed server-validation control renders the error message to the user1
Produces an HtmlTextWriter object to write HTML to the response stream1 This is similar to ASP's Response1Write method; however, the HtmlTextWriter object is much smarter than the raw Write method1 It helps you write well-formed HTML1
By default, save and load view state for all controls as hidden fields on the page1 If you don't want this setting, you can override the SavePageStateFromPersistenceMedium method to save the view state anywhere other than hidden fields1 You will also have to override the LoadPageStateFromPersistenceMedium method to have the saved view states loaded back onto the page prior to rendering1
The UserControl class is similar to the Page class (see the previous section) with the omission of page-specific properties or methods such as ErrorPage, IsValid, User, Validators, MapPath, Validate, and CreateHtmlTextWriter1
The UserControl class is typically used as the base class for custom controls1 We can also build custom controls by inheriting directly from the Control class; however, it's better to start from UserControl because it is not as raw as the Control class1 If you find that UserControl supports a number of properties and methods that you don't really want in your custom control, you might choose to inherit the raw Control class instead1 We show you how to create custom controls in Section 71514 later in this chapter1
If you've done any client-side DHTML scripting, you know how all HTML tags are mapped to scriptable objects1 ASP1NET brings this mapping to the server side1 Before the web page is rendered and sent back the client, you can access and manipulate each of the objects on the page1
ASP1NET maps HTML tags with objects in the hierarchy of server-side classes defined in the System1Web1UI1HtmlControls namespace1 These server objects are called HtmlControls because they closely map to standard HTML elements1
For example, here is a simple HTML page that relies on client-side scripting to change the output page dynamically1 (This page won't run on browsers that do not support VBScript client-side scripting or browsers that have client-side scripting turned off1)
<l> <head> <script language=vbscript> sub cmd1_onclick( ) txtMessage1InnerHtml = _ "(Client-side) Your name is: " & frm11txtName1value end sub </script> </head> <body> <form id=frm1> Enter Name: <input id="txtName" type="text" size="40"> <input type=button id="cmd1" value="Click Me"> <span id="txtMessage"></span> </form> </body> <l>
We will convert this page so that it relies on server control instead of the IE Document Object Model1 Since the output of the page is controlled from the server side, the page works regardless of what kind of browser you are using1 One drawback to this is that all interaction with the page requires a postback to the server1
To take advantage of server controls mapping, all you have to do is to add the id and runat attributes, and your server-side script will be able to access and manipulate the server controls:
<l> <head> <script id="scr1" language="c#" runat="server"> void svr_cmd1_onclick(Object o, EventArgs e) { txtMessage1InnerHtml = "(Server-side) Your name is: " + txtName1Value; } </script> </head> <body> <form id="frm1" runat="server"> Enter Name: <input id="txtName" type="text" size="40" runat="server"> <input type="button" id="cmd1" value="Click Me" onserverclick="svr_cmd1_onclick" runat="server"> <span id="txtMessage" runat="server"></span> </form> </body> <l>
By adding the runat="server" attribute to the HTML form and its controls, you have exposed an HtmlForm object, an HtmlInputText object, an HtmlInputButton object, and an HtmlGenericControl object (the span) to your server-side script, as depicted in Figure 7-11 As you can see in the previous script, you can manipulate the HtmlGenericControl object's txtMessage to set its InnerHtml property1
Even though the results of the two simple examples appear to be the same, they are drastically different from the technical point of view1 Client-side scripting, as the name implies, runs in the client browser process1 On the other hand, when we have controls tagged to run on the server, we can have accesses to other server resources1
Most classes in the System1Web1UI1HtmlControls namespace are derivatives of the HtmlControl class, which in turn derives from the Control class of the System1Web1UI namespace1 See Figure 7-2 for a graphical presentation of the hierarchy1 The HtmlControl class serves as the base class for these HtmlControls because most HTML elements share common characteristics that are defined in this HtmlControl base class1 They share properties such as ID, Disabled, Value, Style, and TagName1 Because these HtmlControls ultimately are derivatives of the Control class, they also have methods and events that the Control class exposes1
Table 7-1 maps the HtmlControls to standard HTML tags1 This means when you have an HTML tag that is flagged to run on the server side with runat="server", ASP1NET creates an appropriate HtmlControl that you can program against1
HTMLControl |
Description |
HTML tag |
---|---|---|
<img> | ||
<input type="hidden"> | ||
Image input |
<input type="image"> | |
<input type="radio"> | ||
<input type="text"> | ||
<input type="button"> | ||
<input type="checkbox"> | ||
Form tag |
<form> | |
Miscellaneous generic HTML tags |
<span, div, etc1> | |
A row in a table | ||
<a href= 1 1 1 > or <a name= 1 1 1 > | ||
HTML button |
While providing HtmlControls, which map to standard HTML elements, ASP1NET also provides another group of UI controls, the WebControl class (see Figure 7-3)1 In addition to providing all traditional controls similar to HtmlControls, WebControls also provide much richer controls such as calendars, grids, and validators1
WebControls are richer, more powerful, and more flexible than HtmlControls1 It seems that it is the natural choice for new ASP1NET applications; however, HtmlControls are better if you are migrating ASP applications1 Another thing that might make you consider using HtmlControls is that with it, your client-side scripts can still access and manipulate the objects1
Most classes in this namespace are based on WebControl, which is again a derivative of the Control class1 The WebControl class provides the common properties and methods inherited by all of its descendants, including access key, tab index, tool tip, color, font, and border setting1