ASP.NET Web Forms

I l @ ve RuBoard

To see how Web Forms work, let's create an ASP.NET version of the HTML form you saw earlier. To create an ASP.NET Web Form, you select the ASP.NET Web Application template from the Visual J# Projects in the New Project dialog box, as shown in Figure 16-6.

The ASP.NET application will need to run under the ASP.NET runtime, which in turn will need the facilities of a Web server such as that provided by IIS. Therefore, the application files (including the Visual Studio .NET project files) will be created in a new virtual directory under IIS. The name of the directory will be the name of the project, and you can define which server you want to create the directory on. As you create the ASP.NET project, Visual Studio .NET will contact the given server and arrange for an appropriate virtual directory to be created. This virtual directory will be set up with the correct IIS settings to allow the executable parts of the Web application to run.

Figure 16-6. Selecting an ASP.NET Web application in the Visual Studio .NET New Project dialog box

As with any Web-based project in Visual Studio .NET, this application will be created on a Web server at the given URL. By default, the project will already contain a Web Form called WebForm1 . You can rename this Web Form or delete it and then add a new Web Form to the project with the required name.

Note

As you'll soon see, a Web Form consists of two parts: an ASPX file containing HTML and controls, and an associated JSL file containing the J# code. If you choose to rename WebForm1.aspx under Visual Studio .NET, this will also rename the associated WebForm1.aspx.jsl file. But be aware that the class name in the JSL file will remain as WebForm1 unless you explicitly change it. You might also need to change the Start Page defined within the Debugging Configuration Properties of the project to ensure that it points to your new file.


The resulting project is shown in Figure 16-7. This figure also shows the Toolbox containing controls that you can use to populate the Web Form.

Figure 16-7. You can drag controls from the Toolbox onto the design view of an ASP.NET Web application.

To re-create the form you saw in FeedsHowMany.htm, you can use two TextBox controls, two Label controls, and a Button control. (Be sure to select these from the Web Forms list in the Toolbox.) You'll end up with something similar to Figure 16-8.

Figure 16-8. The basic cake consumer form as an ASP.NET Web Form

At this stage, it's worth looking at what was produced before we proceed further. The HTML generated as part of this Web Form is shown in FeedsHowMany.aspx (version 1). This Web Form is an early snapshot of code that will evolve into the FeedsHowMany.aspx page provided as a sample file in the FourthCoffee project. You should note two things about this Web page:

  • The contents of the form have changed. The form now uses server-side controls instead of HTML tags.

  • There is no explicit server-side code in this form except for the Page directive at the top of the page.

We'll examine both of these mysteries in turn.

FeedsHowMany.aspx (version 1)
 <%@Pagelanguage="VJ#" Codebehind="FeedsHowMany.aspx.jsl" AutoEventWireup="false" Inherits="FourthCoffee.FeedsHowMany" %> <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML4.0Transitional//EN" > <HTML> <HEAD> <metaname="GENERATOR" Content="MicrosoftVisualStudio7.0"> <metaname="CODE_LANGUAGE" Content="VJ#"> <metaname="vs_defaultClientScript" content="JavaScript(ECMAScript)"> <metaname="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <bodyMS_POSITIONING="GridLayout"> <formid="FeedsHowMany" method="post" runat="server"> <asp:TextBoxid="Size" style="Z-INDEX:101;LEFT:117px; POSITION:absolute;TOP:40px" runat="server" Width="69px" Height="20px"></asp:TextBox> <asp:TextBoxid="Filling" style="Z-INDEX:104;LEFT:116px; POSITION:absolute;TOP:65px" runat="server" Width="69px" Height="20px"></asp:TextBox> <asp:Labelid="Label2" style="Z-INDEX:103;LEFT:19px; POSITION:absolute;TOP:63px" runat="server" Width="86px" Height="25px">Filling</asp:Label> <asp:Labelid="Label1" style="Z-INDEX:102;LEFT:18px; POSITION:absolute;TOP:37px" runat="server" Width="86px" Height="25px">Size</asp:Label> <asp:Buttonid="Calculate" style="Z-INDEX:105;LEFT:35px; POSITION:absolute;TOP:97px" runat="server" Width="133px" Height="25px" Text="Calculate"></asp:Button> </form> </body> </HTML> 

The Server-Side Controls

Instead of traditional HTML <INPUT> tags, the text boxes and button for the form are represented by <asp:TextBox> and <asp:Button> tags, respectively. The text labels also have ASP tags ( <asp:Label> ) rather than ordinary HTML. All of these tags have the attribute runat="server" to indicate that they're processed on the server. Indeed, the whole form is labeled as runat="server" . Controls marked in this way are called server-side controls . The .NET Framework provides a variety of server-side controls, which are defined in the System.Web.UI.WebControls namespace.

A server-side control provides an ASP.NET developer with the same type of functionality as the equivalent control you'd use when building a Windows-based application, including design-time functionality. In Visual Studio .NET, you can drag and drop server-side Web controls onto a Web Form, change their properties, and hook up events just as you would if the controls were controls housed in a Windows Form. Later, you'll see how this simplifies event handling and interaction with the user .

One thing to note about server-side controls is that they do not require any special libraries installed on the client. A server-side control is responsible for representing itself in the client browser by generating standard HTML (and possibly script code) that can be downloaded to the client and rendered there. For example, consider what happens when a client browser accesses the Feeds ­HowMany.aspx page. The actual HTML sent to the client is shown in Feeds ­HowMany.htm (version 1 client side). As you can see, the server-side TextBox , Label , and Buttons controls have presented themselves as standard HTML <INPUT> and <SPAN> tags, and there are no runat="server" attributes anywhere to be seen. The server-side controls detect the client browser capabilities and generate output appropriate to that browser (in this case, Internet Explorer 6). This representation can be HTML 3.2 for a "down-level" browser or Dynamic HTML for Internet Explorer 5.5 or later.

The browser detection and adaptation of the server-side controls offers a great benefit. It means that you don't have to maintain multiple versions of your page for different browsers, nor do you have to create a " lowest common denominator" page that can be represented in all browsers.

FeedsHowMany.htm (version 1 client side)
 <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML4.0Transitional//EN" > <HTML> <HEAD> <metaname="GENERATOR" Content="MicrosoftVisualStudio7.0"> <metaname="CODE_LANGUAGE" Content="VJ#"> <metaname="vs_defaultClientScript" content="JavaScript(ECMAScript)"> <metaname="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <bodyMS_POSITIONING="GridLayout"> <formname="FeedsHowMany" method="post" action="FeedsHowMany.aspx" id="FeedsHowMany"> <inputtype="hidden" name="__VIEWSTATE"  value="dDwtMTE2MDIxNDc1NTs7PrwNYdg2U4LNokc3ysIeaWJtZ2/B" /> <inputname="Size" type="text" id="Size" style="height:20px;width:69px;Z-INDEX:101;LEFT:117px; POSITION:absolute;TOP:40px" /> <inputname="Filling" type="text" id="Filling" style="height:20px;width:69px;Z-INDEX:104;LEFT:116px; POSITION:absolute;TOP:65px" /> <spanid="Label2" style="height:25px;width:86px;Z-INDEX:103; LEFT:19px;POSITION:absolute;TOP:63px">Filling</span> <spanid="Label1" style="height:25px;width:86px;Z-INDEX:102; LEFT:18px;POSITION:absolute;TOP:37px">Size</span> <inputtype="submit" name="Calculate" value="Calculate" id="Calculate" style="height:25px;width:133px;Z-INDEX:105; LEFT:35px;POSITION:absolute;TOP:97px" /> </form> </body> </HTML> 

The Code Behind the Page

The other aspect of the Web Form is the code to be run on the server. In this case, the server-side code associated with the Web Form is held in a separate file. The name and contents of this file are defined in the <%@ Page %> directive in the ASPX page:

 <%@Pagelanguage="VJ#" Codebehind="FeedsHowMany.aspx.jsl" AutoEventWireup="false" Inherits="FourthCoffee.FeedsHowMany" %> 

The notable parts of this directive are the language attribute, which specifies that the code for the page is written in Visual J# (VJ#), and the Codebehind attribute, which indicates an associated JSL file that contains all of the code used in this page. The code in the J# file is referred to as the code behind the page , or simply the code-behind . The contents of this code-behind file are shown in FeedsHowMany.aspx.jsl (version 1). This file contains a standard J# class that inherits from a Web Forms “specific superclass, System.Web.UI.Page , which represents the environment and events required by an ASP.NET page. All of the controls that were added in the design view are represented in the J# class as protected member variables :

 protectedSystem.Web.UI.WebControls.TextBoxSize; protectedSystem.Web.UI.WebControls.LabelLabel1; protectedSystem.Web.UI.WebControls.LabelLabel2; protectedSystem.Web.UI.WebControls.ButtonCalculate; protectedSystem.Web.UI.WebControls.TextBoxFilling; 

An event handler method, Page_Load , is provided for the page load event. You can use this to initialize any dynamic parts of the page. This method is specified as a handler for the Load event for this Page in the InitializeComponent method:

 privatevoidInitializeComponent() { this.add_Load(newSystem.EventHandler(this.Page_Load)); } 

Other events that can be handled include initialization, rendering, and error conditions.

FeedsHowMany.aspx.jsl (version 1)
 packageFourthCoffee; importSystem.Collections.*; importSystem.ComponentModel.*; importSystem.Data.*; importSystem.Drawing.*; importSystem.Web.*; importSystem.Web.SessionState.*; importSystem.Web.UI.*; importSystem.Web.UI.WebControls.*; importSystem.Web.UI.HtmlControls.*; /** *SummarydescriptionforFeedsHowMany. */ publicclassFeedsHowManyextendsSystem.Web.UI.Page { protectedSystem.Web.UI.WebControls.TextBoxSize; protectedSystem.Web.UI.WebControls.LabelLabel1; protectedSystem.Web.UI.WebControls.LabelLabel2; protectedSystem.Web.UI.WebControls.ButtonCalculate; protectedSystem.Web.UI.WebControls.TextBoxFilling; privatevoidPage_Load(System.Objectsender,System.EventArgse) { //Putusercodetoinitializethepagehere } protectedvoidOnInit(System.EventArgse) { // //CODEGEN:ThiscallisrequiredbytheASP.NETWebFormDesigner. //Donotremovethis. // InitializeComponent(); super.OnInit(e); } #regionWebFormDesignergeneratedcode /** *RequiredmethodforDesignersupport-donotmodify *thecontentsofthismethodwiththecodeeditor. */ privatevoidInitializeComponent() { this.add_Load(newSystem.EventHandler(this.Page_Load)); } #endregion } 

By default, Visual Studio .NET will create an assembly containing your code-behind classes and will store it in the bin directory below your Web application's directory. The Inherits attribute of the <%@ Page %> directive indicates the name of the class that contains the code-behind for this ASPX file. The class must inherit from the System.Web.UI.Page class, as shown in FeedsHowMany.aspx.jsl (version 1). When the runtime needs to load this class, it will search initially for an assembly in the bin directory. ASP.NET does not follow the default probing rules listed in Chapter 2, so if it does not find the required class in the bin directory, it will search the Global Assembly Cache (GAC) before giving up. If you want to include additional locations in which to search for assemblies, you must add this to your Web.config file using a probing element.

The following example searches for assemblies in the bin and myAssemblies directories under the virtual directory:

 <configuration> <runtime> <assemblyBindingxmlns="urn:schemas-microsoft-com:asm.v1"> <probingprivatePath="bin;myAssemblies"/> </assemblyBinding> </runtime> </configuration> 

If you're using an alternative search path , you'll also need to specify the name of any assembly you want to include. One option is to use the <%@ Assembly %> directive in the appropriate page:

 <%@AssemblyName="FourthCoffee" %> 

Alternatively, you can link it into the whole application using the assemblies element in the Web.config file:

 <compilation defaultLanguage="VJ#"  debug="true"> <assemblies> <addassembly="FourthCoffee"/> </assemblies> </compilation> 

When an ASPX page is first accessed, its code-behind is located. The ASP.NET runtime then combines the class from the code-behind with the contents of the ASPX file to create a new J# class that inherits from the code-behind class. All of the text-based content of the ASPX page is represented in J# code, which includes the generation of the plain HTML text and tags from the ASPX file. As a result, the whole page becomes a single J# class that can be compiled into Microsoft Intermediate Language (MSIL) and stored in a new assembly. This sequence of events is shown in Figure 16-9. This new class and assembly are used by the ASP.NET runtime to service subsequent requests for the page. This eliminates the need to interpret script or even open extra files when servicing a client request.

Figure 16-9. Combining parts of a Web Form to create an ASP.NET class to service client requests

The files for the generated class and its assembly are stored in the folder \Windows\Microsoft.NET\Framework\.NETVersion\Temporary ASP.NET Files. If you examine this folder, you should find a subfolder with the same name as the folder in which your ASP.NET application resides. If the ASP.NET runtime detects any change in the ASPX files in your application or in their code-behind assembly, it will regenerate the appropriate derived class and recompile it to create a new assembly. All of this happens without you having to do anything!

Caution

Be careful if you decide to rely on automatic compilation. By default, the dependency is on the ASPX file itself and the assembly in which the code-behind resides rather than the source file (the JSL file). This means that changes to the source file will not trigger a recompilation of the assembly by the ASP.NET runtime. To make the automatic compilation dependent on the source file, you must set the Src attribute in the <%@ Page %> directive to point to the source file. This changes the dependency target and means that both the original assembly and the derived assembly will be regenerated if the source file changes.


At this stage, some readers who have an ASP background (and even some who don't) might be wondering what benefit all this offers. Well, the answer is simple:

  • Separating the code and the HTML makes the application more maintainable . The code can be maintained by programmers and the HTML by Web designers, without too many worries about interfering with each other's work. However, the code and the HTML still form one logical unit for development and deployment.

  • The compilation and caching model considerably improves the performance of ASP.NET pages compared to equivalent ASP pages that are interpreted.

  • The use of server-side controls simplifies the creation of sophisticated user interfaces in Web browsers, including not only the display and positioning of controls, but also handling events generated by them (as you'll see in the next section).

Handling Events

You now have a Web Form that displays an HTML form in the Web browser. The next step is to make it do something! As discussed previously, this would be rather tortuous in the pre-ASP.NET model. ASP.NET server-side controls make this much easier. If you're using Visual Studio .NET, it's as simple as double-clicking on the Calculate button shown earlier in Figure 16-8. This will switch you to the code view and generate a Calculate_Click event handler for you to populate. Under the covers, the Forms Designer will add code in the InitializeComponent method to hook up this event handler method to the Calculate button's Click event:

 this.Calculate.add_Click(newSystem.EventHandler(this.Calculate_Click)); 

In Visual Studio .NET, the InitializeComponent method is hidden in a region of the JSL file marked "Web Form Designer generated code." Expand the code and examine it, but remember: Look but don't touch!

The Calculate_Click method is wrapped in a System.EventHandler delegate before being added to the Button control's Click event. You can do this sort of thing yourself if you need to subscribe to events manually. Once the event is hooked up, you can populate the Calculate_Click method with a simplified version of the "feeds how many" calculation:

 privatevoidCalculate_Click(System.Objectsender,System.EventArgse) { booleanfruitFilling= (Filling.get_Text().Equals("fruit"))?true:false; doublemunchSizeFactor=(fruitFilling?2.5:1); intnumConsumers= (int)(Integer.parseInt(Size.get_Text())*munchSizeFactor); } 

Recall from FeedsHowMany.aspx.jsl (version 1) that the Web Form has two TextBox controls, one called size and one called filling . The contents of these controls are retrieved by using the Text property. The contents of the Size TextBox are converted into an integer to be used as part of the calculation. At the end of the method, you have the number of consumers, but the question is how to get this back to the user.

One option, as with original ASP, is to use Response.Write at the end of the method:

 this.get_Response().Write("Thiscakefeeds " +numConsumers+ " people"); 

Although this is serviceable, it is not very user friendly. The question arises of where this message will be written. Figure 16-10 shows that this message will appear at the top of the page.

Figure 16-10. Sending information to the user using Response.Write

If you were to use a simple text-writing mechanism, you'd have to do any necessary text formatting by adding HTML tags into the string returned. To gain more control over the location and style of the message, you can take advantage of a Label server-side control to display the message. If you add another Label to your Web Form called Output , you can set the text in this control once you've performed your calculation:

 Output.set_Text("Thiscakefeeds " +numConsumers+ " people"); 

Because the Label is an ordinary control in Visual Studio, you can set its properties ”the foreground and background colors, the text size, and so on ”all without generating a single HTML tag yourself. Indeed, you don't even have to write any code to change these properties. You can just alter them by using the Properties pane of Visual Studio .NET. The example uses this mechanism to set the foreground and background color of the Output Label . The result is shown in Figure 16-11.

Figure 16-11. Using a label control to display messages

You should have noticed in the previous two figures that the values entered into the filing and size fields retained their contents even though the page went through a round-trip to the server to perform the calculation. No extra code was added to do this ”the TextBox control took care of it. Each control has an EnableViewState property, and when it is set to true (the default), the form containing the controls will send down a hidden form field called __VIEWSTATE that contains a unique value. The state of each control is cached on the server and associated with this value so that each control's last known state can be retrieved automatically when it is rendered. The full code for this Web Form is shown in FeedsHowMany.aspx.jsl (version 2). This is the version provided as part of the sample page FeedsHowMany.aspx in the FourthCoffee project.

FeedsHowMany.aspx.jsl (version 2)
 packageFourthCoffee; importSystem.Collections.*; importSystem.ComponentModel.*; importSystem.Data.*; importSystem.Drawing.*; importSystem.Web.*; importSystem.Web.SessionState.*; importSystem.Web.UI.*; importSystem.Web.UI.WebControls.*; importSystem.Web.UI.HtmlControls.*; /** *SummarydescriptionforFeedsHowMany. */ publicclassFeedsHowManyextendsSystem.Web.UI.Page { protectedSystem.Web.UI.WebControls.TextBoxSize; protectedSystem.Web.UI.WebControls.LabelLabel1; protectedSystem.Web.UI.WebControls.LabelLabel2; protectedSystem.Web.UI.WebControls.ButtonCalculate; protectedSystem.Web.UI.WebControls.LabelOutput; protectedSystem.Web.UI.WebControls.TextBoxFilling; privatevoidPage_Load(System.Objectsender,System.EventArgse) { } protectedvoidOnInit(System.EventArgse) { // //CODEGEN:ThiscallisrequiredbytheASP.NETWebFormDesigner. //Donotremovethis. // InitializeComponent(); super.OnInit(e); } #regionWebFormDesignergeneratedcode /** *RequiredmethodforDesignersupport-donotmodify *thecontentsofthismethodwiththecodeeditor. */ privatevoidInitializeComponent() { this.Calculate.add_Click(newSystem.EventHandler(this.Calculate_Click)); this.add_Load(newSystem.EventHandler(this.Page_Load)); } #endregion privatevoidCalculate_Click(System.Objectsender,System.EventArgse) { booleanfruitFilling= (Filling.get_Text().Equals("fruit"))?true:false; doublemunchSizeFactor=(fruitFilling?2.5:1); intnumConsumers= (int)(Integer.parseInt(Size.get_Text())*munchSizeFactor); Output.set_Text("Thiscakefeeds " +numConsumers+ " people"); } } 

Client-Side Validation

As you've seen, ASP.NET provides a powerful server-based model for client interaction that makes developing Web applications quicker and easier. However, developer convenience is not the only consideration. Sending data back and forth between client and server is an expensive operation compared with local processing, especially if the client and server communicate over the Internet. Consequently, data should be processed on the client if possible rather than sent back to the server each time processing is needed. Naturally, it is not possible or even desirable to migrate a lot of application logic to the client. But there might be some functionality that can be safely and easily migrated to the client, thereby improving the performance of the application.

An example of such functionality is validating the contents of the fields in an HTML form. If you want, you can write client-side script to validate the contents of your form fields, but ASP.NET provides several server-side controls that can simplify this task. The most straightforward technique is to use a validator. You select a RequiredFieldValidator on the Web controls tab of the Visual Studio .NET Toolbox and associate it with a TextBox . You drag and drop the RequiredFieldValidator from the Toolbox onto the design surface of the Web Form. You position the RequiredFieldValidator where appropriate and set its ErrorMessage property to the message you want displayed using the Properties window.

The RequiredFieldValidator is transparent, so when it is not displaying an error message, the user won't see it. The error message is shown in the RequiredFieldValidator when validation fails, so be sure to allow enough room for it to be displayed. To associate the RequiredFieldValidator with the TextBox , you locate the ControlToValidate property in the Properties window and set it to the name of the associated TextBox . (Visual Studio .NET will provide a drop-down list of controls that you can validate.)

The following HTML was generated by Visual Studio .NET as part of the FeedsHowManyWithValidation.aspx page after we associated a RequiredFieldValidator with a TextBox by manipulating them graphically on the design surface:

  <asp:TextBoxid="Filling  " style="Z-INDEX:108;LEFT:117px;POSITION: absolute;TOP:40px" runat="server" Width="69px" Height="20px"> </asp:TextBox> <  asp:RequiredFieldValidator  id="RequiredFieldValidator2" style="Z-INDEX: 107;LEFT:214px;POSITION:absolute;TOP:69px" runat="server" Width="173px" Height="20px"  ControlToValidate="Filling"  ErrorMessage="Pleaseentercakefilling" Visible="True"> </asp:RequiredFieldValidator> 

In the preceding example, the RequiredFieldValidator is associated with the TextBox whose id is " Filling". The RequiredFieldValidator checks whether the TextBox is empty. If the TextBox is empty, the RequiredFieldValidator will display its error message and the form will not be submitted to the server. The result of running this ASPX page is shown in Figure 16-12.

Figure 16-12. You can use validators to set individual validation error messages for particular fields in a Web Form.

There's no magic involved in client-side validation ”an ASP.NET page containing validator controls generates client-side script to perform the validation, much as you could write yourself if you so desired. The generated code is shown in the listing FeedsHowManyWithValidation Generated HTML.

FeedsHowManyWithValidation Generated HTML
 <!DOCTYPEHTMLPUBLIC "-//W3C//DTDHTML4.0Transitional//EN" > <HTML> <HEAD> <metaname="GENERATOR" Content="MicrosoftVisualStudio7.0"> <metaname="CODE_LANGUAGE" Content="VJ#"> <metaname="vs_defaultClientScript" content="JavaScript (ECMAScript)"> <metaname="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"> </HEAD> <bodyMS_POSITIONING="GridLayout"> <formname="FeedsHowMany" method="post" action="FeedsHowManyWithValidation.aspx" language="javascript" onsubmit="ValidatorOnSubmit();" id="FeedsHowManyWithValidation"> <inputtype="hidden" name="__VIEWSTATE" value="dDwtMjEwMTcyNjU1Ozs+LtpMd81aKMttUkt3FmSaFMPWsKA=" /> <  scriptlanguage="javascript"  src="/aspnet_client/system_web/1_0_3705_0/WebUIValidation.js"></script> <inputname="Size" type="text" id="Size" style="height:20px;width:69px;Z-INDEX:109;LEFT:117px; POSITION:absolute;TOP:40px" /> <spanid="RequiredFieldValidator2" controltovalidate="Filling"  errormessage="Pleaseentercakefilling" evaluationfunction="RequiredFieldValidatorEvaluateIsValid"  initialvalue="" style="color:Red;height:20px;width:173px; Z-INDEX:108;LEFT:214px;POSITION:absolute;TOP:69px; visibility:hidden;">Pleaseentercakefilling</span> <inputname="Filling" type="text" id="Filling" style="height:20px;width:69px;Z-INDEX:103;LEFT:116px; POSITION:absolute;TOP:65px" /> <spanid="Label2" style="height:25px;width:86px;Z-INDEX:102; LEFT:19px;POSITION:absolute;TOP:63px">Filling</span> <spanid="Label1" style="height:25px;width:86px;Z-INDEX:101; LEFT:18px;POSITION:absolute;TOP:37px">Size</span> <inputtype="submit" name="Calculate" value="Calculate" onclick="if(typeof(Page_ClientValidate)=='function')  Page_ClientValidate()  ; " language="javascript" id="Calculate" style="height:25px;width:133px;Z-INDEX:104;LEFT:35px; POSITION:absolute;TOP:97px" /> <spanid="Output" style="color:Yellow;background-color:#C0C0FF; font-weight:bold;height:69px;width:167px;Z-INDEX:105; LEFT:18px;POSITION:absolute;TOP:136px"></span> <spanid="RequiredFieldValidator1" controltovalidate="Size"  errormessage="Pleaseentercakediameter" evaluationfunction="RequiredFieldValidatorEvaluateIsValid"  initialvalue="" style="color:Red;height:20px;width:172px; Z-INDEX:107;LEFT:212px;POSITION:absolute;TOP:42px; visibility:hidden;">Pleaseentercakediameter</span>  <scriptlanguage="javascript"> <!-- varPage_Validators= newArray(document.all["RequiredFieldValidator2"], document.all["RequiredFieldValidator1"]); //--> </script> <scriptlanguage="javascript"> <!-- varPage_ValidationActive=false; if(typeof(clientInformation)!= "undefined" && clientInformation.appName.indexOf("Explorer")!=-1){ if(typeof(Page_ValidationVer)== "undefined") alert("Unabletofindscriptlibrary '/aspnet_client/system_web/1_0_3705_0/WebUIValidation.js'. Tryplacingthisfilemanually,orreinstallbyrunning 'aspnet_regiis-c'."); elseif(Page_ValidationVer!= "125") alert("ThispageusesanincorrectversionofWebUIValidation.js. Thepageexpectsversion125.Thescriptlibraryis " + Page_ValidationVer+ "."); else ValidatorOnLoad(); } functionValidatorOnSubmit(){ if(Page_ValidationActive){ ValidatorCommonOnSubmit(); } } //--> </script>  </form> </body> </HTML> 

We won't dwell on the precise syntactic details of the generated page, but the client-side code essentially works as follows :

  • It contains a script tag that downloads a common ASP.NET JavaScript file, WebUIValidation.js, which contains a script to perform client-side validation. This file can be found in the folder \Inetpub\ wwwroot \aspnet_client\system_web\.NETVersion\.

  • The form containing the controls has its onsubmit event mapped to the ValidatorOnSubmit method that's defined in the client-side script. This method checks whether validation is required and then calls a standard validation function defined in WebUIValidation.js.

  • Each validator is transformed into a hidden <span> element with attributes defining its associated control, the type of validation required (as defined by which standard JavaScript function to call), and its error message.

  • All of the validators on the page are defined in an array, Page_Validators , so the client-side script can find them easily.

If you leave either of the text fields on the form blank, this client-side code will display a screen similar to the one shown earlier in Figure 16-12.

The types of validation controls are as follows:

  • RequiredFieldValidator

    Makes sure the user does not leave a value unset.

  • RangeValidator

    Ensures that a value is between set limits.

  • CompareValidator

    Compares the value to a constant value or the value of another field. For example, you can use this control to ensure that a start time is less than a finish time.

  • RegularExpressionValidator

    Ensures that a value matches a fixed pattern, such as an e-mail address ( name @ host ).

If none of the available validators meet your requirements, you can implement your own validation by creating a CustomValidator and implementing client-side and server-side validation routines. Note that the standard validation controls can operate on both the client side and the server side. Usually, validation errors are caught early on the client side using the JavaScript-based mechanisms shown previously. If the client-side validation fails, the contents of the form will not be sent to the server. However, it is not always possible to use client-side validation.

The main objective of validation is to catch validation errors as early as possible. Ideally, all validation problems will have been fixed before the form is submitted to the server. However, the server-side part of the validation control will always perform its own validation when the form is received, to ensure that no accidental or malicious submission of invalid fields occurs. The server-side validation is especially important if client-side JavaScript is disabled in the browser. There is no way of knowing this without performing multiple round-trips, so the use of server-side validation acts as a failsafe mechanism. Note also that the HTML Document Object Model (DOM) of some browsers might be different from that expected by the validation control, in which case the validation control might not generate any client-side validation script and might simply rely on the server-side validation.

You can display all of your validation error messages in one place using the ValidationSummary control. This will poll all of the validators on the page to see whether their validation has failed. (Remember the Page_Validators array mentioned earlier?) If it has, the ValidationSummary will display the validator's failure message as part of its own output. The ValidationSummary can display its output in the main HTML page, in a message box, or both.

Figure 16-13 shows the output from the sample file FeedsHowManyWithValidationSummary.aspx. This page contains a ValidationSummary that displays the error information for both the size and filling validators. To achieve this result, you can drag and drop a ValidationSummary onto the Web Form design surface in an appropriate location. When the form is submitted, the ValidationSummary will poll all of the validators on the page to determine whether any validation errors occurred.

By default, the ValidationSummary displays a set of bullet points, each showing the ErrorMessage property of any validator on the page that has flagged an error. You can specify a meaningful message to display before this bulleted list by setting the ValidationSummary control's HeaderText property using the Visual Studio .NET Properties window. To ensure that the same information is not displayed twice, the Text property of the validators has been set to a single asterisk ( * ) so that the offending fields are just highlighted. (It can be blank if you want.) The ValidationSummary can also display its content as a list or as a single paragraph.

Figure 16-13. Using a ValidationSummary to display a validation error message

ASP.NET controls generally use client-side script where appropriate to reduce network round-trips and thus improve application performance. You can also use many other approaches for client-side scripting in your application, but an in-depth discussion of these approaches is beyond the scope of this chapter.

I l @ ve RuBoard


Microsoft Visual J# .NET (Core Reference)
Microsoft Visual J# .NET (Core Reference) (Pro-Developer)
ISBN: 0735615500
EAN: 2147483647
Year: 2002
Pages: 128

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