Recipe 3.2 Using the Enter Key to Submit a Form After Validation

     

3.2.1 Problem

You want to use the Enter key to submit the information entered by a user to the server, but your form uses client-side validation that must be performed before the form is submitted.

3.2.2 Solution

Write code that generates some JavaScript that captures the keypress event in the browser, checks to see if the key pressed is the Enter key, performs the client-side validation, and then submits the form.

In the .aspx file, add id and runat attributes to the body element so that all the tag's contents can be accessed (and modified) in the code-behind:

 <body id="pageBody" runat="server"       leftmargin="0" marginheight="0" marginwidth="0" topmargin="0"> 

In the code-behind class for the page, use the .NET language of your choice to:

  1. Call the Add method of the pageBody object's Attributes collection to add the onload attribute to the pageBody control, which causes the captureKeyPress (or equivalently named) client-side script function to be called when the page is first loaded. Your goal is to have HTML like this sent to the browser:

     <body id="pageBody" leftmargin="0" marginheight="0" marginwidth="0"        topmargin="0" onload="captureKeyPress( );"> 

  2. Build a string containing the client-side JavaScript that is to be executed when the page is loaded and causes it to be output as part of the rendered page; the client-side script must capture the keypress event in the browser, check to see if the key pressed is the Enter key, perform the client-side validation, and perform the form submittal:

     <script language='javascript'> <!--   function captureKeyPress( )   {     document.onkeypress = checkForReturn;   }   function checkForReturn( )   {     if (window.event.keyCode==13)      {       if (window.event.srcElement.id!='btnCancel')        {         if (typeof(Page_ValidationActive) != 'undefined')         {           if (Page_ValidationActive)           {             if (Page_ClientValidate( ))             {               window.event.keyCode=0;               _  _doPostBack('btnSave','');             }           }         }       }     }   } //--> </script> 

  3. Use the RegisterClientScriptBlock method of the Page object to register the script block so that it is output when the page is rendered.

Example 3-4 through Example 3-6 show the .aspx and code-behind files for an application that implements this solution.

3.2.3 Discussion

In its use of client script to capture the keypress event of the browser document object and watch for use of the Enter key, this solution is like the one we present in Recipe 3.1. What is unique is the way this solution leverages the JavaScript functions provided in the ASP.NET WebUIValidation.js . ASP.NET automatically includes this file in rendered pages that use client-side validation. As its name implies, WebUIValidation.js is a script library that contains functions housing all of the logic that ASP.NET uses for client-side validation. Indeed, every validation control emits a standard block of client script into the page, whose function is to call relevant code in WebUIValidation.js . The validation script library is referenced with the following code, which ASP.NET generates automatically and which you can see when you view the source of a rendered page:

 <script language="javascript"   src="/aspnet_client/system_web/1_1_4322/WebUIValidation.js"> </script> 

The value for the src attribute will vary depending on the version of ASP.NET installed on the web server. However, because this value is automatically generated by ASP.NET when the page is rendered, you can ignore it.


From here on, we concentrate on the validation code used in our example, because that is what is unique about this recipe. See Recipe 3.1 for an explanation of the base code that the two examples share.

In this example, we have added RequiredFieldValidator controls, which perform as their name implies and are highlighted in the code listing shown in Example 3-4. Validators are described in Chapter 2.

The client-side JavaScript generated by this example is shown next . The generated code is similar to the JavaScript in Recipe 3.1, but includes additional code to be processed after the key is identified as the Enter key, provided the Cancel button does not have the focus when Enter is pressed.

 <script language='javascript'> <!--   function captureKeyPress( )   {     document.onkeypress = checkForReturn;   }   function checkForReturn( )   {     if (window.event.keyCode==13)      {       if (window.event.srcElement.id!='btnCancel')        {  if (typeof(Page_ValidationActive) !=  'undefined')   {   if (Page_ValidationActive)   {   if (Page_ClientValidate( ))   {   window.event.keyCode=0;   _  _doPostBack('btnSave','');   }   }   }  }     }   } //--> </script> 

In the preceding code, a check is made to ensure the validation functions are included in the rendered page. Next, a check is made to ensure validation is active.

If the validation functions are included in the rendered page and validation is active, the client-side validation is performed.

If the client validation passes the tests defined by the validators on the page, the event keycode is set to 0 to stop further processing of the keypress event, and the page is posted back.

The code-behind in Examples 3.2 and 3.3 has been altered to build the client script in a separate routine, generateClientScript , so it can be called by more than one method. The only change to the code used to generate the client-side JavaScript in those examples is in the code that generates the checkForReturn function ”it now includes the extra checks mentioned earlier and performs validation.

The example code shown in this recipe provides a more efficient approach to generating the client script than that in Example 3-2 and Example 3-3. In the Page_Load method, a check is made to see if the form is being posted back to the server. If it is, the client script is not generated in the Page_Load method, providing the ability to decide if the page will be redisplayed and thus requiring the client script to be generated in the Save and Cancel button click events. If another page is to be displayed after processing the Save or Cancel click events, the call to generate the client script should not be made, saving unnecessary work.


3.2.4 See Also

Recipe 3.1; Chapter 2 for form validation examples

Example 3-4. Using the Enter key to submit a form after validation (.aspx)
 <%@ Page Language="vb" AutoEventWireup="false"           Codebehind="CH03EnterSubmitWithValidationVB.aspx.vb"           Inherits="ASPNetCookbook.VBExamples.CH03EnterSubmitWithValidationVB" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html>   <head>     <title>Using Enter To Submit Form With Validation</title>     <link rel="stylesheet" href="css/ASPNetCookbook.css">   </head>   <body id="pageBody" runat="server"         leftmargin="0" marginheight="0" marginwidth="0" topmargin="0">     <form id="frmEnterCapture" method="post" runat="server">       <table width="100%" cellpadding="0" cellspacing="0" border="0">         <tr>           <td align="center">             <img src="images/ASPNETCookbookHeading_blue.gif">           </td>         </tr>         <tr>           <td class="dividerLine">             <img src="images/spacer.gif" height="6" border="0"></td>         </tr>       </table>       <table width="90%" align="center" border="0">         <tr>           <td><img src="images/spacer.gif" height="10" border="0"></td>         </tr>         <tr>           <td align="center" class="PageHeading">             Using Enter To Submit Form With Validation (VB)           </td>         </tr>         <tr>           <td><img src="images/spacer.gif" height="10" border="0"></td>         </tr>         <tr>           <td align="center">             <table border="0">               <tr>                 <td class="LabelText">Email Address: </td>                 <td>                   <asp:TextBox ID="txtEmailAddress" Runat="server"                                 Columns="30" CssClass="LabelText" />  <asp:requiredfieldvalidator id="rfvLoginID"   runat="server"   controltovalidate="txtEmailAddress"   cssclass="AlertText"   display="Dynamic"   enableclientscript="True">   <img src="images/arrow_alert.gif"> Email Address Is Required   </asp:requiredfieldvalidator>  </td>               </tr>               <tr>                 <td class="LabelText">Password: </td>                 <td>                   <asp:TextBox ID="txtPassword" Runat="server"                                 textmode="Password"                                Columns="30" CssClass="LabelText" />  <asp:requiredfieldvalidator id="rfvPassword"   runat="server"   controltovalidate="txtPassword"   cssclass="AlertText"   display="Dynamic"   enableclientscript="True">   <img src="images/arrow_alert.gif"> Password Is Required   </asp:requiredfieldvalidator>  </td>               </tr>               <tr>                 <td colspan="2">                   <br>                   <table align="center" width="50%">                     <tr>                       <td align="center">                         <asp:ImageButton ID="btnLogin" Runat="server"                              CausesValidation="True"                              ImageUrl="images/buttons/button_login.gif" />                       </td>                       <td align="center">                         <asp:ImageButton ID="btnCancel" Runat="server"                              CausesValidation="False"                              ImageUrl="images/buttons/button_cancel.gif" />                       </td>                     </tr>                   </table>                 </td>               </tr>             </table>           </td>         </tr>       </table>     </form>   </body> </html> 

Example 3-5. Using the Enter key to submit a form after validation code-behind (.vb)
 Option Explicit On  Option Strict On '----------------------------------------------------------------------------- ' '   Module Name: CH03EnterSubmitWithValidationVB.aspx.vb ' '   Description: This module provides the code behind for   '                CH03EnterSubmitWithValidationVB.aspx ' '***************************************************************************** Imports Microsoft.VisualBasic Imports System.Environment Imports System.Text Namespace ASPNetCookbook.VBExamples   Public Class CH03EnterSubmitWithValidationVB     Inherits System.Web.UI.Page     'controls on form     Protected pageBody As System.Web.UI.HtmlControls.HtmlGenericControl     Protected WithEvents btnLogin As System.Web.UI.WebControls.ImageButton     Protected WithEvents btnCancel As System.Web.UI.WebControls.ImageButton     '*************************************************************************     '     '   ROUTINE: Page_Load     '     '   DESCRIPTION: This routine provides the event handler for the page load     '                event.  It is responsible for initializing the controls     '                on the page.     '-------------------------------------------------------------------------     Private Sub Page_Load(ByVal sender As System.Object, _                           ByVal e As System.EventArgs) Handles MyBase.Load  If (Not Page.IsPostBack) Then   generateClientScript( )   End If  End Sub  'Page_Load     '*************************************************************************     '     '   ROUTINE: btnLogin_Click     '     '   DESCRIPTION: This routine provides the event handler for the login      '                button click event.  It is responsible processing the     '                form data.     '-------------------------------------------------------------------------     Private Sub btnLogin_Click(ByVal sender As Object, _                                ByVal e As System.Web.UI.ImageClickEventArgs) _             Handles btnLogin.Click  If (Page.IsValid) Then   'perform login operations here and redirect to the next page   Else   'generate the client JavaScript since the page was not valid and   'must be redisplayed   generateClientScript( )   End If  End Sub  'btnLogin_Click     '*************************************************************************     '     '   ROUTINE: btnCancel_Click     '     '   DESCRIPTION: This routine provides the event handler for the cancel      '                button click event.     '-------------------------------------------------------------------------     Private Sub btnCancel_Click(ByVal sender As Object, _                                 ByVal e As System.Web.UI.ImageClickEventArgs) _             Handles btnCancel.Click       'perform cancel operations here     End Sub  'btnCancel_Click     '*************************************************************************     '     '   ROUTINE: generateClientScript     '     '   DESCRIPTION: This routine generates the client-side JavaScript used     '                to capture the Enter key and process it as a form      '                submittal     '-------------------------------------------------------------------------     Private Sub generateClientScript( )       Dim clientScript As StringBuilder       Dim functionScript As String       'add onload attribute to the page body to add a handler to the       'keypress event for the page       pageBody.Attributes.Add("onload", _                               "captureKeyPress( );")       'generate the opening script tag       clientScript = New StringBuilder       clientScript.Append("<script language='javascript'>" & NewLine)       clientScript.Append("<!--" & NewLine)       'add the client script used to capture the keypress event       functionScript = "document.onkeypress = checkForReturn;" & NewLine       clientScript.Append("function captureKeyPress( )" & NewLine)       clientScript.Append("{" & NewLine)       clientScript.Append(functionScript)       clientScript.Append("}" & NewLine)       'add the client script to check the keypress event  functionScript = "if (window.event.keyCode==" & Asc(NewLine) & ") " & _   "{" & NewLine & _   "if (window.event.srcElement.id!='" & btnCancel.ID & "') " & _   "{" & NewLine & _   "if (typeof(Page_ValidationActive) != 'undefined')" & NewLine & _   "{" & NewLine & _   "if (Page_ValidationActive)" & NewLine & _   "{" & NewLine & _   "if (Page_ClientValidate( ))" & NewLine & _   "{" & NewLine & _   "window.event.keyCode=0;" & NewLine & _   GetPostBackClientEvent(btnLogin, "") & ";" & NewLine & _   "}" & NewLine & _   "}" & NewLine & _   "}" & NewLine & _   "}" & NewLine & _   "}" & NewLine  clientScript.Append("function checkForReturn( )" & NewLine)       clientScript.Append("{" & NewLine)       clientScript.Append(functionScript)       clientScript.Append("}" & NewLine)       'generate the closing script tag       clientScript.Append("//-->" & NewLine)       clientScript.Append("</script>" & NewLine)       'register the client script to be output when the page is rendered       Page.RegisterClientScriptBlock("ScriptBlock", _                                      clientScript.ToString( ))     End Sub  'generateClientScript   End Class  'CH03EnterSubmitWithValidationVB End Namespace 

Example 3-6. Using the Enter key to submit a form after validation code-behind (.cs)
 //---------------------------------------------------------------------------- // //   Module Name: CH03EnterSubmitWithValidationCS.aspx.cs // //   Description: This module provides the code behind for //                CH03EnterSubmitWithValidationCS.aspx // //**************************************************************************** using System; using System.Text; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace ASPNetCookbook.CSExamples {   public class CH03EnterSubmitWithValidationCS : System.Web.UI.Page   {     // controls on form     protected System.Web.UI.HtmlControls.HtmlGenericControl pageBody;     protected System.Web.UI.WebControls.ImageButton btnLogin;     protected System.Web.UI.WebControls.ImageButton btnCancel;     //************************************************************************     //     //   ROUTINE: Page_Load     //     //   DESCRIPTION: This routine provides the event handler for the page      //                load event.  It is responsible for initializing the      //                controls on the page.     //------------------------------------------------------------------------     private void Page_Load(object sender, System.EventArgs e)     {       // wire the login and cancel button click events       this.btnLogin.Click += new ImageClickEventHandler(this.btnLogin_Click);       this.btnCancel.Click +=          new ImageClickEventHandler(this.btnCancel_Click);  if (!Page.IsPostBack)   {   generateClientScript( );   }  }  // Page_Load     //************************************************************************     //     //   ROUTINE: btnLogin_Click     //     //   DESCRIPTION: This routine provides the event handler for the login      //                button click event.  It is responsible processing the     //                form data.     //------------------------------------------------------------------------     private void btnLogin_Click(Object sender,                                 System.Web.UI.ImageClickEventArgs e)     {  if (Page.IsValid)   {   // perform login operations here and redirect to the next page   }   else   {   // generate the client JavaScript since the page was not valid and   // 'must be redisplayed   generateClientScript( );   }  }  // btnLogin_Click     //************************************************************************     //     //   ROUTINE: btnCancel_Click     //     //   DESCRIPTION: This routine provides the event handler for the cancel      //                button click event.     //------------------------------------------------------------------------     private void btnCancel_Click(Object sender,       System.Web.UI.ImageClickEventArgs e)     {       // perform cancel operations here     }  // btnCancel_Click     //************************************************************************     //     //   ROUTINE: generateClientScript     //     //   DESCRIPTION: This routine generates the client-side JavaScript used     //                to capture the Enter key and process it as a form      //                submittal     //------------------------------------------------------------------------     private void generateClientScript( )     {       const char NEW_LINE = '\r';       StringBuilder clientScript = null;       String functionScript = null;       // add onload attribute to the page body to add a handler to the       // keypress event for the page       pageBody.Attributes.Add("onload",                               "captureKeyPress( );");       // generate the opening script tag       clientScript = new StringBuilder( );       clientScript.Append("<script language='javascript'>" + NEW_LINE);       clientScript.Append("<!--" + NEW_LINE);       // add the client script used to capture the keypress event       functionScript = "document.onkeypress = checkForReturn;" + NEW_LINE;       clientScript.Append("function captureKeyPress( )" + NEW_LINE);       clientScript.Append("{" + NEW_LINE);       clientScript.Append(functionScript);       clientScript.Append("}" + NEW_LINE);       // add the client script to check the keypress event  functionScript = "if (window.event.keyCode==" +   System.Convert.ToByte(NEW_LINE).ToString( ) + ") " +   "{" + NEW_LINE +   "if (window.event.srcElement.id!='" + btnCancel.ID + "') " +   "{" + NEW_LINE +   "if (typeof(Page_ValidationActive) != 'undefined')" + NEW_LINE +   "{" + NEW_LINE +   "if (Page_ValidationActive)" + NEW_LINE +   "{" + NEW_LINE +   "if (Page_ClientValidate( ))" + NEW_LINE +   "{" + NEW_LINE +   "window.event.keyCode=0;" + NEW_LINE +   GetPostBackClientEvent(btnLogin, "") + ";" + NEW_LINE +   "}" + NEW_LINE +   "}" + NEW_LINE +   "}" + NEW_LINE +   "}" + NEW_LINE +   "}" + NEW_LINE;  clientScript.Append("function checkForReturn( )" + NEW_LINE);       clientScript.Append("{" + NEW_LINE);       clientScript.Append(functionScript);       clientScript.Append("}" + NEW_LINE);       // generate the closing script tag       clientScript.Append("//-->" + NEW_LINE);       clientScript.Append("</script>" + NEW_LINE);       // register the client script to be output when the page is rendered       Page.RegisterClientScriptBlock("ScriptBlock",                                       clientScript.ToString( ));     }  // generateClientScript   }  // CH03EnterSubmitWithValidationCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2006
Pages: 179

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