What Are Server Controls?


As seen in Chapter 4, ASP.NET is designed around the concept of server controls. This stems from the fundamental change in the philosophy for creating interactive pages. In particular, with the increasing power of servers and the ease of building multi-server web farms, we can circumvent the problems of handling the increasing range of different client devices by doing much more of the work on the server.

We also end up with a client interface that looks and behaves much more like a traditional application. However, to understand how the use of server controls affects the way we build applications, it is important to grasp the way that the new ASP.NET page model changes the whole approach to web page design.

The ASP.NET Page Model Revisited

Before the advent of ASP.NET, the traditional way of creating pages dynamically has always been as shown in Figure 5-1:

click to expand
Figure 5-1:

The process can be described as follows :

  1. Capture the request in IIS and pipe it through a parsing engine like the ASP interpreter. This is achieved by setting the script mappings in IIS to direct all requests for .asp pages to the asp.dll ASP ISAPI DLL.

  2. Within the interpreter ( asp.dll ), examine the page for server-side script sections. Non-script sections are simply piped back out to the client through the response. Script sections are extracted and passed to an instance of the appropriate scripting engine.

  3. The scripting engine executes the code and sends any output that this code generates to the response, at that point in the page.

The problem is that the code usually ends up resembling spaghetti. It is difficult to get a well-structured design when all we are doing is interpreting the blocks of script that can be placed almost anywhere in the page.

ASP.NET Pages Are All about Events

If you think about how a traditional Windows executable application is created, it all depends on events. You create a form or window for the user to work with, and place in it the controls they will use to accomplish the required task. We create handlers for events that are raised as the user interacts with the controls and the page. The code in each event handler is responsible for updating the page or controls, creating output, or carrying out whatever task is required (see Figure 5-2):

click to expand
Figure 5-2:

The great thing with ASP.NET is that, in conjunction with server controls and the new page model, you can build web pages and applications that work in an event-driven manner. In other words, you now have a proper event-driven architecture.

ASP.NET Is Compiled Code

Much of the theory of this new page structure was covered in previous chapters, so we will confine ourselves to the actual server controls themselves in this chapter. The important concept to grasp is that the whole page (all of the HTML, text, and other content) is compiled into a class. This class can then be executed to create the output for the client.

All the static or client-based content (text, HTML, client-side script, and so on) is sent to the client through the response when the class is executed. This content cannot be accessed using server-side code. However, all controls or elements that are marked with the runat ="server" attribute are themselves created as objects within the page class. This means that you can write code that uses these objects. To put it more simply, if you mark an element or control as being runat="server" , you can access its properties, call its methods , and react to the events it raises on the server. This works because ASP.NET uses <form> elements to create the postback architecture described in earlier chapters. In the postback architecture, the page and its contents are posted back to the same ASP.NET file on the server when the user interacts with the controls on that page.

Server Controls Are Event-Driven

When a user clicks a button that is defined as a server control on a page, the values of the controls on that page are posted back to the server and an event is raised (on the server). We react to this event using a server-side event handler. For example, we can define a button control in the following way:

  <input type="submit" value="Go" onserverclick="MyFunction"   runat="server" />  

Then, on the server, we react to the click event (notice that the attribute name is onserverclick , not onclick , which is defined in HTML 4.0 to raise a client-side event):

  <script language="VB" runat="server">   Sub MyFunction(objSender As Object, objArgs As EventArgs)    ... code to handle the event here ...    End Sub   </script>  

Server Controls Are Objects within the Page

Another point that might seem obvious, but which is again at the heart of the new page design, is that each server control is compiled into the page class as an object that is globally available within the page. This means that, within an event handler, you can access all the controls on the page. So, as in a traditional application, you can access the values in other textboxes, buttons , list controls, and so on, and then take the appropriate actions and/or create the appropriate output. The following listing shows an example where the Page_Load event is used to collect values from several server controls.

  <div id="divResult" runat="server" />   ...   <script language="VB" runat="server">   Sub Page_Load()   Dim strResult As String   strResult = "MyTextBox.ID = " & MyTextBox.ID & "<p />"   strResult += "MyTextBox.Value = " & MyTextBox.Value & "<p />"   strResult += "MyCheckBox.Checked = " & MyCheckBox.Checked   divResult.InnerHtml = strResult   End Sub   </script>  

You can also set the value of the controls, as follows:

  <script language="VB" runat="server">   Sub Page_Load()   Dim datToday As Date = Now()   MyTextBox.Value = datToday   End Sub   </script>  

Experimenting with Server Controls

To show how the various server controls work, we have provided a simple example application that shows the output generated in the browser by each of the controls. You can also set the values of the common properties for each control and see the results.

The example is included in the samples that you can download for this book from http://www.daveandal.net/books/8900/, or run online at the same URL. The application is in the folder named server-controls , and has a default.htm page to start it. This opens the page server-controls.htm , as shown in Figure 5-3:

click to expand
Figure 5-3:

The gray background section in the main right-hand page displays the actual HTML output that the selected control generates. This is done with some client-side JScript, which creates an instance of the XMLHTTP object (an integral part of IE 5) and uses it to fetch the same page again as a string, after the page has finished loading into the right-hand frame of our application. The code then parses out the section containing the output of the server control and displays it (you can view the source of the page to see this code). This means that you will only be able to use IE 5 or above to view this particular example. However, this was felt to be a valid course of action in order to show the actual output of the server controls.

We could simply have queried the OuterHtml property of the element itself to get the HTML content, but this is actually different from the HTML that the browser receives from the server. The IE HTML DOM parses the incoming HTML and sorts and simplifies the attributes, and so you wouldn't see a true picture of the server control's output in this case.

As you can see from Figure 5-3, the left-hand frame contains a collapsible tree listing all the server controls. For each one, you can specify the values for several of the most useful properties for that control. For example, in Figure 5-4 we have selected the HTML Anchor control and set the Title , Href , Name , and Target properties, and then clicked the Update button. You can see the effect this has on the output of the control.

click to expand
Figure 5-4:

We will be using this application throughout this chapter and the next , to demonstrate the various controls. We don't have room to exhaustively examine all the methods and properties for all of the controls, but you can experiment with them to see what effect each of the properties has on the output created by the different server controls.

By comparing the generated output with the property settings you make, you can get a feel for how these controls can be used. It is a relatively simple one-to-one connection between the properties you set and the attributes created with the HTML controls. However, as you will see in the next chapter (particularly with the rich controls described there), the results from the other sets of server controls can be quite different.

About the Example Application

This chapter won't be describing how the example application works; however, the source code is available for you to look through if you want to learn more. All it does is create an instance of the selected control and then display a set of input elements for the properties specific to that control. As the page loads, it reads the values of these properties and inserts them into the input elements. When we set one or more of the properties and click the Update button, the server control is updated to reflect these property values.

We haven't provided inputs for all the properties, as there are a large number that are generic to many controls, and which are not commonly used. Where the property value is taken from an enumeration, such as the ImageAlign property for an ASP:Image control (Figure 5-5), we provide a drop-down list containing the enumeration values. To set the property when the page is submitted, we use the integer value of that enumeration member as stored in the value attribute of the listbox item. We will discuss this in more detail when we look at the ASP.NET Web Form controls in the next chapter. However, you can see how this works if you examine the source code for the page ( asp_image.aspx ).

click to expand
Figure 5-5:

Some of the server controls demonstrated in the application (such as textboxes and lists) are interactive. However, any changes made within the control itself (the control we are demonstrating) are not reflected in the property values shown in the controls where you set these values. For example, if you change the text in the HtmlInputText control at the top of that particular demonstration page, it is reset to the value shown in the Value property input control when you click Update. At any time, you can return the control to its original state by clicking the Reset button.

When Should You Use Server Controls?

One very important topic to consider is when to choose server controls over normal HTML elements. For example, if you want a textbox on a form, should you use a server control or a normal <input type="text"> element? To create a textbox, you have three options. You can use an ordinary HTML element that is displayed as a textbox in the browser, as follows:

  <input type="text" name="mytext" />  

You can use an HtmlInputText server control as well. Again, the type attribute is set to "text" , but this time the runat="server" attribute is included as well:

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

You can use an <asp:TextBox> control (we will discuss the pros and cons of these controls in the next chapter):

  <asp:TextBox id="mytext" runat="server" />  

Adding the runat="server" attribute to an HTML element, or using one of the ASP Web Form controls (which must always include the runat="server" attribute in their definition) causes that control to be compiled into the page, and executed on the server each time the page is requested . This is obviously more resource- intensive than just including some HTML in the page output, as would be the case with an element that does not contain the runat="server" attribute.

However, to be able to access the element's properties, methods, or events in the server-side code, you have to create it as a server control. It is always worth considering which elements actually need to be server controls when you build a page, though. For example, the following situations do not require a server-side control:

  • When the element is used only to run some client-side script. For example, a button that opens a new browser window, or interacts with a client-side ActiveX control or Java applet, or calculates some value for display in the page using DHTML or in an alert dialog.

  • When the element is a Submit button that is only used to submit a form to the server. In this case, the code in the Page_Load() event handler can extract the values from the other controls.

  • When the element is a hyperlink that opens a different page or URL, and there is no need to process the values for the hyperlink on the server.

  • Any other times when access to the element's properties, methods, or events in server-side code is not required.

Remember that you can still use the Request.Form and Request.QueryString collections in the same way as in previous versions of ASP, with both ordinary HTML control elements and with server controls. HTML control elements that are on a <form> but are not marked with runat="server" (in other words, they are not server controls), will still send their values to the server in the Request.Form and Request.QueryString collections when the form is submitted.

In general, a page that uses server controls instead of HTML elements results in something like a 30 percent drop in performance each time the page is generated. However, this is only an average “ you don't get a compounded 30 percent penalty hit for every control. Besides, if you use server-side code to set the values of controls using traditional ASP techniques, you generally get worse performance compared to using the ASP.NET server controls.

The Controls Available in ASP.NET

We are now in a position to appreciate the advantages we get with server controls:

  • HTML output that creates the elements to implement the control in the browser.

  • An object within the page that we can program against on the server.

  • Automatic maintenance of the control's value (or state).

  • Simple access to the control values without having to dig into the Request object.

  • The ability to react to events, and thus create better structured pages.

  • A common approach to building user interfaces as web pages.

  • The ability to more easily address different types of client device.

The server controls provided with the .NET Framework fall quite neatly into six groups:

  • HTML Server Controls :The server-based equivalents of the standard HTML controls. They create output that is the same as the definition of the control within the page, and they use the same attributes as the standard HTML elements. We will be looking at these controls in this chapter.

  • ASP.NET Validation Controls :A set of special controls designed to make it easy to check and validate the values entered into other controls on a page. They perform the validation client- side, server-side, or both, depending on the type of client device that requests the page. We will also be looking at these controls in this chapter.

  • ASP.NET Web Form Controls :A set of controls that are the equivalent of the normal HTML <form> controls, such as a textbox, a hyperlink, and various buttons. They have a standardized set of property names that make life easier at design-time, and easier for graphical page creation tools to build the page. We will see more about these controls in the next chapter.

  • ASP.NET List Controls :These controls provide a range of ways to build lists. These lists can also be data bound. In other words, the content of the list can come from a data source such as an Array, a HashTable, or a range of other data sources. The range of controls provides many different display options, and some include special features for formatting the output and even editing the data in the list. We will see more about these controls in Chapter 7.

  • ASP.NET Rich Controls :These controls (which include the Calendar and Ad Rotator) create complex task-specific output. We will see more about these controls in the next chapter.

  • ASP.NET Mobile Controls :A separate set of controls that provide the same kind of functionality as the Web form, List, and Rich controls, but have specially extended features that completely change the output of the control, depending on the client device that is accessing the page. They are primarily designed to support mobile and small-screen devices, and they can create output that is in Wireless Markup Language ( WML ) as well as HTML and other formats. You will learn more about these controls in Chapter 21.




Professional ASP. NET 1.1
Professional ASP.NET MVC 1.0 (Wrox Programmer to Programmer)
ISBN: 0470384611
EAN: 2147483647
Year: 2006
Pages: 243

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