Server Controls

One of the biggest shifts in the creation of Web applications in VB .NET is the idea of the server control. When teaching students about Visual InterDev over the past few months, I've explained that although the product Visual InterDev is going away, its functionality is being added to the .NET Framework. This means that any language that targets the Framework will have the capability to create Web applications. This might give some of you nightmares, but realize that this means you could write high-performance, dynamic Web applications in COBOL.NET. The server controls are a key component of the Framework, and they are one of the main tools that will be used by any .NET language in order to create Web applications.

If you open Visual Studio .NET, click on the form, and then open the Toolbox, you'll see several interesting tabs. One tab is labeled HTML, and it shows a series of HTML tags. These are just controls that you can drag and drop to your form to create a static HTML page; each element maps directly to an HTML tag. For example, if you were to drag and drop a Table from the HTML tab of the Toolbox and then look at the HTML, the following HTML would be generated (shortened for brevity):

<TABLE cellSpacing=1 cellPadding=1 width=300 border=1>
   <TR>
      <TD>
      </TD>
      <TD>
      </TD>
      <TD>
      </TD>
   </TR>
</TABLE>

Even though you can work with the table in the designer just as you can any other control, the designer is really just writing HTML in the background. That's HTML in the static sense. That means that you can't start writing VB .NET code against that table because it is just some HTML sitting in the page.

Because the elements in the HTML tab map to standard HTML tags, they aren't as powerful as the controls you added earlier. Although the button and text box you added earlier are mapped to standard HTML tags, these are ASP.NET server controls. They act as controls against which you can program just as you would in a Windows form; you double-click on a button, for example, and you wind up in the code window with a Button1_Click event procedure.

Return to your WebAppTest application. In the designer for WebForm1.aspx, click down to the next blank line (you might need to press the Enter key to get to the line below the label and button you added). Drag over a button from the HTML tab of the Toolbox. Now, click on the Web Forms tab and drag over a button from the Toolbox. If you look in the designer, you'll have two buttons side by side, and they look identical except that the second one has the small green triangle in the upper-left corner, indicating that it is a server control.

If you look at the HTML, however, you will see a significant difference. Here are how the two buttons appear in the HTML view (slightly modified to fit the page):

<INPUT type="button" value="Button">
<asp:Button id="Button2" runat="server" Text="Button">
</asp:Button>

The first button is displayed with a standard HTML <INPUT> tag. The second button, however, is displayed with an <asp:Button> tag. This <asp:Button> tag is not standard HTML. Instead, when the .NET compiler sees this, it knows that the button is an ASP.NET server control, and you have basically the same functionality with this control that you would have with the same type of control in a Windows form.

In the Design view, double-click on the first button (the HTML button). When you do this, you'll see the dialog box shown in Figure 8.3. This message box informs you that this is an HTML element, which means you cannot write code for it. However, the box offers you an option: You can convert the button to an HTML server control. There is a distinction between what VS .NET calls an HTML server control and an ASP.NET server control.

Figure 8.3. The message box explains that you cannot add code to an HTML element without first making it an HTML server control.


HTML server controls are standard HTML elements to which Microsoft has added server-side programming capabilities. When you add an HTML element, ASP.NET sees that as just text to be generated and passed to the client. HTML server controls, on the other hand, come with a programming model that exposes all the attributes of the HTML element on the server. Microsoft has made these controls quite powerful: They can maintain values between round-trips to the server, they can respond to events on the server (or, optionally, on the client), and the controls can be bound to a data source.

Don't confuse HTML server controls with the items listed on the HTML tab of the Toolbox. Those items are just HTML tags; they are not HTML server controls. All HTML and ASP.NET server controls will be found on the Web Forms tab of the Toolbox.

ASP.NET server controls are more abstract controls in that they do not necessarily have a single corresponding HTML tag. For example, if you look at the Web Forms tab of the Toolbox, you'll notice controls such as the Calendar and Repeater. Although these controls end up being generated as HTML, they are often composed of many HTML tags. For example, the calendar is a table, with many rows and columns. ASP.NET server controls have all the benefits you saw with the HTML server controls, and they can also determine the capabilities of the client browser and render more or less advanced HTML depending on the client. Some server controls have the ability to delay sending events to the server, instead caching them and sending them when the entire form is submitted.

You can take almost any element on a page and turn it into an HTML server control. For example, when you double-clicked the HTML button, the message box said that you had to convert it into an HTML server control to write code for it. The message box even said that you could right-click on the control and choose Run As Server Control. Behind the scenes, this would add runat="server" to the <INPUT> tag, and allow you to write server-side code based on that tag.

You can turn plain text into an HTML control. For example, you have a heading 1 at the top of the page that proudly proclaims, Welcome to my first ASP.NET page. Switch to the HTML view for a moment and you'll see that the code looks like this:

<H1 align="center">
   Welcome to my first ASP.NET page
</H1>

Now, switch back to the Design view and highlight the text. Right-click on the highlighted text and choose Run As Server Control. Now, switch back to the HTML view and you will see that the HTML has changed to this:

<H1 align="center" id="H11" runat="server">
   Welcome to my first ASP.NET page
</H1>

Although this doesn't immediately look like a big change, two attributes have been added to the tag: id="H11" and runat="server". The first attribute makes this tag an object against which you can write some code. This is a common practice when writing Dynamic HTML (DHTML). The second attribute, however, tells the ASP.NET engine that this object's code will run on the server side. So, the server will handle any properties or methods or events on this element.

Double-click on the second button you added (the HTML server control). In the code window, in the Button2_Click event handler, type the following code:

Private Sub Button2_Click(ByVal sender As System.Object, _
 ByVal e As System.EventArgs) Handles Button2.Click
   H11.InnerText = "It is now " & Now
End Sub

This code merely replaces the text inside the <H1> tag with the text It is now and then appends the current date and time. If you run the project and click the button, you will get results like those shown in Figure 8.4.

Figure 8.4. Almost any element can be turned into a server control, as this <H1> tag has been in this example.


If your curiosity is getting the better of you, feel free to drag a Calendar ASP.NET server control from the Web Forms tab of the Toolbox and drop it on your form. If you view the code in the HTML view of the designer, you'll see that you have added an <asp:Calendar>tag to the HTML. However, if you run the page and then view the source code that actually reaches the browser, you'll see that the calendar is actually just generated as an HTML table, as the following code snippet shows:

...
Sun
</td><td align="Center">
Mon
</td><td align="Center">
Tue
</td><td align="Center">
Wed
...

Some client-side JavaScript is mixed in as well because the ASP.NET engine realized that the browser was capable of handling it, and sent the code to the browser. Remember, server controls work hard to determine the capabilities of the client browser, and to render HTML and/or JavaScript to give the users the most robust experience possible, given the capabilities of their browser.

Validation Controls

One of the most common requests for any Web application is the ability to perform client-side validation of input. It would have been nice if HTML were written with some sort of mask that could be applied to fields, but that isn't the case. In standard HTML, there is no way to perform validation of data on the client. To get around this problem, most browsers let you mix in some client-side script code, which is capable of performing validation, but the code for this can be tedious to write.

There are a number of reasons for performing validation on the client. First, you give the user a better experience. If you can immediately notify the user that she did not fill in a required field, you just saved her the time it would have taken to submit the form, have the server generate a message to inform her of the problem, and return the error message to her. In addition, using client-side validation lessens network traffic and server load by never sending invalid data to the server. This client-side code helps leverage the fact that, although browsers often act like dumb terminals, they are often running on computers capable of processing code.

Microsoft provides a series of validation controls in ASP.NET that automate client-side form validation. The validation controls in ASP.NET are smart; they will perform the validation at the client if possible. The controls will first determine whether the client can handle DHTML, and if so, they send the code down to the client. If the browser is less capable, the validation code will be executed on the server.

From a development standpoint, however, you code the controls exactly the same way. This means you don't have to dumb down your validation code for less-capable browsers. You can have robust validation code and be assured that the same code will be run for all browsers. It's just that the location of where the code is run changes depending on the capabilities of each browser.

Creating a Project with the Validation Controls

To try out some validation, it is useful to start from scratch. Add a new Web Form to your WebAppTest project and name it UserInfo.aspx. Change UserInfo's pageLayout property to FlowLayout. Click on the Toolbox and drag a text box from the Web Forms tab and drop it on your new Web form. For this new text box, change the (ID) property to txtSSN. Now, on the form, click to the right of the text box so that you can see the cursor. Press the Enter key to move to the next line. Click on the Toolbox, drag a button from the Web Forms tab, and drop it on the line below the text box. Now, from the Web Forms tab of the Toolbox, drag a RequiredFieldValidator control and drop it next to the text box.

The RequiredFieldValidator control checks whether a particular field has been filled in. You place the RequiredFieldValidator on the page, and then tie it to a particular input control, such as a TextBox, CheckBox, or DropDownList. In this case, you want to tie it to the text box. Click once on the RequiredFieldValidator if it is not already the current object. In the Properties window, you will see a property named ControlToValidate. Click here and drop down the list. The only input control that will appear is txtSSN; this is correct, so choose it.

You are ready for your first test. Before you run the page, however, you might be tempted to go to the project properties and choose to make UserInfo.aspx the startup object. However, Web Applications work differently: There is no startup object, per se. Instead, right-click on UserInfo.aspx in the Solution Explorer window and choose Set As Start Page. This notifies Visual Studio .NET which page to run when the user clicks the Start button. It does not change anything in the page itself. Now that you have set UserInfo.aspx as the start page, run the project. The page appears inside Internet Explorer.

After the page is running, click on the button without entering anything in the text box. Immediately, the text RequiredFieldValidator appears to the right of the text box. Now, enter anything into the text box and click the button. The RequiredFieldValidator text goes away, and the entered value stays in the text box. When the RequiredFieldValidator text disappears and the value you typed in the text box remains, it means that the submit action has taken place, which means you have made a round-trip to the server.

The fact that the text stayed in the text box even after a round-trip to the server is important. Before ASP.NET, you would have to have written server-side code to capture field values for you, and then write those values back into the text boxes. ASP.NET handles this automatically, meaning you get this advanced functionality without having to write the code.

If you use IE 4.0 or higher, the validation actually occurs on the client. This allows you to get immediate feedback that the field is blank, when in fact you specified that a value is required. After you fill in the value, you send the data to the server and perform a server round-trip. If you're using a less-capable browser, the code will run on the server.

If you feel that the error message RequiredFieldValidator is not particularly useful, you can modify the error message by changing the properties. You will see this shortly.

Types of Validators

If you look at the Web Forms tab of the Toolbox, you'll see a variety of validator controls. Briefly, they are as follows:

  • RequiredFieldValidator— This validator requires that its ControlToValidate property have a value. In other words, the control to which this validator is tied cannot be left blank.

  • CompareValidator— This validator compares the value the user entered with a value you specify. Your specified value could be a constant, a calculated value, or a value from a database.

  • RangeValidator— This validator requires that entered data be within a particular range. The range can be numeric, dates, currency, or alphabetical.

  • RegularExpressionValidator— Regular expressions are also known as masks. This validator can make sure that entered data matches a particular format, such as the format of phone numbers and Social Security numbers.

  • CustomValidator— This validator uses code you write yourself to validate the data.

  • ValidationSummary— This validator simply reports all the errors encountered by the other validators. You will see an example of this validator shortly.

Applying Multiple Validators to the Same Field

It is possible to apply more than one validator to the same field. For example, you might have a Social Security number field that is both required and must be in a particular format. Close IE, if you still have it running, in order to return to the design mode for the WebAppTest project. Drag a RegularExpressionValidator to the form, next to the RequiredFieldValidator you added earlier. On the RegularExpressionValidator, change the ControlToValidate property to txtSSN, and click on the ellipses on the ValidateExpression property. In the Regular Expression Editor dialog box that pops up, choose U.S. Social Security Number and then click OK.

Run the project, and try these three tests:

  • Do not enter anything, and click the button. You will notice that the RequiredFieldValidator message appears.

  • Enter Hello into the text box and press the button. The RequiredFieldValidator no longer appears because that condition is satisfied. However, the RegularExpressionValidator now appears because you are failing that condition.

  • Enter 111-11-1111 into the text box and click the button. No validator text appears, and you will now see the form make a trip to the server because both validators are satisfied.

In some browsers, such as IE6, the validators run as soon as you tab out of the field, meaning that the user does not even have to wait to click the button to see the errors.

Modifying the Validators

Notice that the text in the validators is not the friendliest text that you could show your clients. If you return to design mode, click the RequiredFieldValidator in the Design pane, and look at the properties, you'll notice a property named ErrorMessage. Change this property to This field is required. Next, click on the RegularExpressionValidator and change its ErrorMessage property to SSN must be in ###-##-#### format.

Now, run the page again, and repeat the same three tests from the last section. You should get validator messages for the first two tests, but the text displayed should be the new values you entered in the ErrorMessage property of each validator.

You'll also notice that even when the RequiredFieldValidator is not displayed, the RegularExpressionValidator appears far enough to the right that you can tell where the RequiredFieldValidator appears. That is because the validators have a Display property, and its default value is Static. If you change this property to Dynamic for the RequiredFieldValidator and run the page again, you'll see that the ReqularExpression Validator now appears next to the text box when it is displayed. The Dynamic value says that the field will not take up any space unless it is displayed. This is supported by IE 4.0 and higher, but support on other browsers might not exist. In those cases, the validator fields will work as they did when you had the property set to Static.

Providing a Validation Summary

It is possible simply to mark the fields that failed their validations with a symbol and provide a summary of all the validations at the top or bottom of the page. The ValidationSummary control allows you to build just such a list of all the errors that occurred.

To see this work, you will want to modify the UserInfo.aspx quite a bit. Add text before the first box identifying it as the Social Security Number field. Drop down to the next line and add the text First Name and then add a TextBox ASP.NET server control. After you add the text box, change its ID property to something meaningful, such as txtFName. Now, go to the next line, type Last Name, add a TextBox ASP.NET server control, and give it a meaningful name. Add the following additional labels and controls, and give the text boxes meaningful names by setting the (ID) properties:

  • Address 1

  • Address 2

  • City

  • State

  • Zip

  • Phone

Now, add a RequiredFieldValidator next to First Name, Last Name, Address 1, City, State, and Zip. That means the Address 2 and Phone fields are optional. Make sure that you bind the RequiredFieldValidators to the correct text boxes.

Next to the Phone text box, add a RegularExpressionValidator and set the ValidationExpression property to U.S. Phone Number, and bind this to the Phone Number text box. At this point, your form will look something like what you see in Figure 8.5.

Figure 8.5. A more complex data entry screen with validator server controls.


Now, change the text on the validators so that they make sense. For example, on the RequiredFieldValidator for the First Name text box, set the ErrorMessage property to The First Name field is required. Change all the validators this way, including the RequiredFieldValidator for the Social Security Number field you added a while ago. When you are done, run the project. After it is running, press the button without entering anything. You should get a page like the one shown in Figure 8.6.

Figure 8.6. The data entry form is now being run, showing most of the validator messages.


As you can see in Figure 8.6, this can be a cumbersome way to show the errors. Instead, you might want to have a listing of all the errors in one place. That's where the ValidationSummary control comes into play. Add an extra line between the Phone text box and the button. Drag a ValidationSummary control onto the form and drop it above the button but after the Phone text box and validator. Highlight the control on the form, change the HeaderText property to The following errors occurred:, and then run the form. Click the button without entering anything, and you will see that the validator messages appear next to each text box, and the same messages appear in the ValidationSummary at the bottom of the page. Having this validation summary at the bottom can be handy, but do you need the same message beside each text box and in the summary? Usually not.

Return to the designer and on each validator tied to a field, change the Text property to an asterisk (*). Do not change anything in the ValidationSummary. Now, run the page again. If you press the button without filling in any fields, you will get an asterisk next to the required fields, but the ErrorMessage text you entered for each validator still appears in the ValidationSummary control.

In Figure 8.7, some fields have been entered, but some have not. In addition, the Phone field has been entered incorrectly. Notice the results in the ValidationSummary field.

Figure 8.7. The ValidationSummary control allows you to show all the validation errors in one place and, optionally, to mark each field.


You can see that the fields that have been entered properly do not have any indicator next to them. Those that are incorrect have an asterisk by them, and the error messages are listed in the validation summary at the bottom of the page. This provides a very easy, powerful mechanism for handling form validation. In the past, the alternative was client-side code that examined each field and then displayed error messages to the user. Here, you have gained the same functionality without writing any code.

Creating ASP.NET Pages Without Visual Studio .NET

So far, you have been creating ASP.NET pages with Visual Studio .NET. This was certainly not the case for traditional ASP developers. While Microsoft did have Visual InterDev, many ASP developers continued to use Notepad as their editor of choice.

Given the richness of the VS .NET environment, and the support for full programming languages in ASP.NET, many developers are expected to create their ASP.NET applications in VS .NET. However, you do not have to create your pages in VS .NET. You can still create them using Notepad, as these examples will show you.

Creating a Simple ASP.NET Page with Notepad

Open Notepad (or any other text editor of your choice) and enter the following code. Don't worry that this HTML doesn't have all the standard HTML sections; it is still valid HTML as far as Internet Explorer is concerned.

<html>
   <h1>Hello, world!</h1>
</html>

You'll also notice there is no code here. However, you'll still save the file with an .aspx extension. Choose File, Save, and place the file in the directory in which you have created WebAppTest. By default, this is c:InetpubwwwrootWinAppTest, but this could vary. Before saving the file, make sure to change the Save as type drop-down list box to All Files. Then, name the file NotepadTest.aspx and save it.

After saving the file, open IE and enter the URL for the file, in this format:

http://<servername>/webapptest/notepadtest.aspx

The page should load in the browser without errors. This shouldn't be too surprising because .NET just compiled the page and saw everything was static HTML, so that is all that was generated in response to the client request.

Now, edit the page in Notepad. Your new code should look like this:

<html>
   <h1 id="myHeader" runat="server">Hello, world!</h1>
   <script language="vb" runat="server">
      Sub Page_Load(Source As Object, e As EventArgs)
         myHeader.InnerText="Changed in Code"
      End Sub
   </script>
</html>

In this code, you have first changed the header into a scriptable element, by adding an ID attribute and telling ASP.NET to run it at the server. Then, you added a script block and threw in some VB .NET code. When the page is loading, you change the InnerText property of myHeader. To verify that this is happening, run this page, and you will see that everything works fine.

Adding Controls

You just created a simple example, and made an element of the page scriptable by giving it an ID attribute. You can continue to do this, or you can use the richer server controls. As you saw in the previous section, the tags are somewhat different for a server control. Modify your code to look like this:

<html>

<form id="Form1" method="post" runat="server">
   <h1 id="myHeader" runat="server">Hello, world!</h1>
   <asp:Label id="lblDateTime" runat="server">Hello</asp:Label>
   <p>
   <asp:Button id="btnDateTime" runat="server"
               text="Click Me" Onclick="btnDateTime_Click" />


   <script language="vb" runat="server">
      Sub Page_Load(Source As Object, e As EventArgs)
         myHeader.InnerText="Changed in Code"
      End Sub

      Sub btnDateTime_Click(Source As Object, e As EventArgs)
         lblDateTime.Text = Now
      End Sub
   </script>
</form>
</html>

What you have done is add two server controls: a label and a button. You've set some properties of these controls, and then you've added code to handle the click event of the button. Run the page and verify that when you click the button, the label shows the current date and time.

This is just a quick example of how you can create your ASPX pages using a simple text editor. For the rest of the chapter, you will return to using VS .NET.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.147.20