Thursday, October 6, 2011

jQuery.Ajax versus Server-side event handler

This sample demonstrates two ways of getting address from the server: using server-side event handler versus calling jQuery.Ajax

The following is the markup that provides two fields with javascript call on the change event. It also provides a button that is wired to a server side methode:

     <div>

         <h3> Address Test</h3>

         tabbing from the textboxes will verify if calling the webservice is required.

         <table  width="100%"><tr><td><table><tr>

                             <td> Huisnummer *</td>

                             <td><div class="FieldContainer">

                                     <asp:TextBox  runat="server"  ID="textboxHousenumber"  ClientIDMode="Static"

                                         CssClass="TextField TextField02" onchange="VerifyAddress();"

                                         ValidationGroup="KlantAddress" />

                                 </div>

                             </td></tr><tr>

                             <td> Postcode *</td>

                             <td><div  class="FieldContainer">

                                     <asp:TextBox  runat="server"  ID="textboxPostcode"      ClientIDMode="Static"

                                                 CssClass="TextField TextField02"  

                                                 MaxLength="7"  onchange="VerifyAddress();"

                                                 ValidationGroup="KlantAddress" 

                                                 />

                                 </div>

                             </td></tr>

                     </table>

                   Server side call:<br  />

                     <asp:Button  ID="Button1"  runat="server"  OnClick="ShowAddress"  Text="Get Adres"  ToolTip="CustomerDataController"  />

                     <asp:Label  runat="server"  ID="lblAddress"  />

                   

 

Assume we have a we DBLLayer that provides an address or throws an exception.
The event handler would be something like this:

 

     /// <summary>Server side event handler</summary>

     public  void  ShowAddress(object  sender, EventArgs  e)

     {

         try

         {

             var  adres = DBLayer.GetAddress(textboxPostcode.Text, textboxHousenumber.Text);

             ShowAdres(adres);

         }

         catch  (Exception  ex)

         {

             LogError("Error :- "  + ex.Message);

         }

     }

 

And the Javascript will look like this:

 

     function  VerifyAddress() {

         // This method is calling the ShowAddress only if both parameters are filled in.  

         $("#<%=lblAddress.ClientID %>" ).text("" );

         var  postcode = $("#<%=textboxPostcode.ClientID %>" ).val();

         var  huisnummer = $("#<%=textboxHousenumber.ClientID %>" ).val();

         if  (postcode && huisnummer && parseInt(huisnummer) > 0) {

             $("#<%=lblAddress.ClientID %>" ).text("calling the server" );

             var  data = "{ postcode:'"  + postcode + <span' , huisnummer: "  + huisnummer + " }" ;

             jQuery.ajax({

                 type: <span' ,

                 contentType: <span'application/json;' ,

                 data: data,

                 dataType: <span' ,

                 url: <span' ,

                 success: OnGetAddressComplete,

                 error: OnErrorReceived

             });

         }

     }

     function  OnErrorReceived(xhr, ajaxOptions, thrownError) {

         var  message = jQuery.parseJSON(xhr.responseText);

         $("#<%=lblAddress.ClientID %>" ).text(

             "ERROR ("  + xhr.status + ") - "  + message.Message);

     }

     function  OnGetAddressComplete(result) {

         // display the result

         var  adres = result.d;

         $("#<%=lblAddress.ClientID %>" ).text(

             adres.Straat + <span''  +

             adres.Huisnummer + <span','  +

             adres.Postcode + <span''  + adres.Plaats);

     }

And finally the webservice will be like:

 

     [System.Web.Services.WebMethod ()]

     public  static  Adres GetAddress(string  postcode, string  huisnummer)

     {

         if  (!IsPostcode(postcode))

             throw  new  Exception ("Invalid Postcode." );

         int  hNr = 0;

         if  (!Int32 .TryParse(huisnummer, out  hNr))

             throw  new  Exception ("Invalid house number." );

         var  result = DBLayer .GetAddress(postcode, huisnummer);

         if  (result == null )

             throw  new  Exception (" Unknown address." );

         return  result;

     }

    

     public static bool IsPostcode(string  zipcode)

     {

         var  ZipcodeRegex = @"^[1-9][0-9]{3}[a-zA-Z]{2}[\\s]*$" ;

         Regex  r = new  Regex (ZipcodeRegex, RegexOptions .IgnoreCase);

         Match  m = r.Match(zipcode);

         return  m.Success;

     }