Microsoft Ajax CDN and the jQuery Validation Library

Scott Guthrie announced the launch of the Microsoft Ajax CDN on his blog last night. If you have not read his post, I recommend that you read it now to get a general overview of the CDN and how you can take advantage of the CDN to improve the performance of your ASP.NET Web Forms and ASP.NET MVC applications:

http://weblogs.asp.net/scottgu/archive/2009/09/15/announcing-the-microsoft-ajax-cdn.aspx

“The Microsoft Ajax CDN enables you to significantly improve the performance of ASP.NET Web Forms and ASP.NET MVC applications that use ASP.NET AJAX or jQuery.  The service is available for free, does not require any registration, and can be used for both commercial and non-commercial purposes.

ASP.NET 4.0 will make it especially easy for ASP.NET Web Forms developers to take advantage of the CDN. By setting one property of the ScriptManager control – EnableCdn=true, you will be able to redirect all requests for the built-in ASP.NET JavaScript files to the CDN and improve the performance of your Web Forms applications.”

In his announcement, Scott describes how both the ASP.NET Ajax and the jQuery libraries are included in the CDN. There is one more set of JavaScript files that are added to the CDN today that Scott did not announce: the jQuery Validation library.

If you are not familiar with the jQuery Validation library then you should know that this is one of the most popular form validation libraries used by jQuery developers. Microsoft is shipping the jQuery validation library with both ASP.NET Web Forms and ASP.NET MVC in Visual Studio 2010.  Furthermore, jQuery Validation library will be integrated with ASP.NET MVC.

Via Microsoft Ajax CDN and the jQuery Validation Library

How to handle JSON dates returned by ASP.NET AJAX

 

The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when directly calling ASP.NET AJAX web services and page methods.

Unlike every other data type in the language, JavaScript offers no declarative method for expressing a Date. Consequently, embedding them within JSON requires a bit of fancy footwork. More… How I handle JSON dates returned by ASP.NET AJAX | Encosia

A quick introduction of using jTemplate against AJAX JSON data

 

jQuery has a few template plugins, the most widely accepted is jTemplate. jTemplate is a JQuery template engine that works with AJAX and JSON data. We can use jTemplate in the following steps:

First, download the JQuery JavaScript file and reference it in your web page:

  1. <scrip src="scripts/jQuery-jtemplates.min.js" type="text/javascript"></script>

<scrip src="scripts/jQuery-jtemplates.min.js" type="text/javascript"></script>

Second, define your template:

image

  1. <script type="text/html" id="TemplateResultsTable">  
  2. {#template MAIN}  
  3. <table  cellpadding="10" cellspacing="0">  
  4.   <tr>  
  5.     <th>Artist</th>  
  6.     <th>Company</th>  
  7.     <th>Title</th>  
  8.     <th>Price</th>  
  9.   </tr>  
  10.   {#foreach $T.d as CD}  
  11.     {#include ROW root=$T.CD}  
  12.   {#/for}  
  13. </table>  
  14. {#/template MAIN}  
  15. {#template ROW}  
  16. <tr class="{#cycle values=['','evenRow']}">  
  17.   <td>{$T.Artist}</td>  
  18.   <td>{$T.Company}</td>  
  19.   <td>{$T.Title}</td>  
  20.   <td>{$T.Price}</td>  
  21. </tr>  
  22. {#/template ROW}  
  23. </script> 

Please note that we define the template in a script block, which can be accessed by its id; also, $T is a reference to the data item passed to the template.

Third, call your web service in your script, designate the template and instantiate it with data.

  1. $(document).ready(function() {  
  2.           $.ajax({  
  3.               type: "POST",  
  4.               url: "CDCatalog.asmx/GetCDCatalog",  
  5.               data: "{}",  
  6.               contentType: "application/json; charset=utf-8",  
  7.               dataType: "json",  
  8.               success: function(msg) {  
  9. //instantiate a template with data
  10.                   ApplyTemplate(msg);   
  11.               }  
  12.           });  
  13.       });  
  14. function ApplyTemplate(msg) {  
  15.       $(‘#Container’).setTemplate($("#TemplateResultsTable").html());  
  16.       $(‘#Container’).processTemplate(msg);  
  17. }

For more info please visit Xun Ding’s excellent article Using jQuery with ASP .NET

Consuming an ASP.NET web service or page method using jQuery

The following is a dummy ASP .NET web service. Please note that this service is adorned with the ScriptService attribute that makes it available to JavaScript clients.

Listing 2: A Dummy web service
  1. [WebService(Namespace = "http://tempuri.org/&quot;)]  
  2. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  3. [System.Web.Script.Services.ScriptService]  
  4. public class dummyWebservice : System.Web.Services.WebService  
  5. {  
  6.   [WebMethod()]  
  7. public string HelloToYou(string name)  
  8.   {  
  9. return "Hello " + name;  
  10.   }  
  11.   [WebMethod()]  
  12. public string sayHello()  
  13.   {  
  14. return "hello ";  
  15.   }    

For example, we can call a specific web method in a web service as such.

Listing 4: JQuery .ajax command
  1.   $.ajax({  
  2.   type: "POST",  
  3.   contentType: "application/json; charset=utf-8",  
  4.   url: "WebService.asmx/WebMethodName",  
  5.   data: "{}",  
  6.   dataType: "json"
  7. }); 

Two things are worth noting in the above JQuery AJAX call. First, we must specify the contentType’s value as application/json; charset=utf-8, and the dataType as json; second, to make a GET request, we leave the data value as empty.

So put it together, the following code demonstrates how we would use JQuery to call the web service we created above.

Listing 5: Calling a web service using jQuery
  1. <%@ Page Language="C#" %>
  2. <%@ Import Namespace="System.Web.Services" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
  4. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
  5. <html >
  6. <head id="Head1" runat="server">
  7. <title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
  8. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js"&gt;
  9. </script>
  10. <script type="text/javascript">
  11.       $(document).ready(function() {  
  12.          $("#sayHelloButton").click(function(event){  
  13.              $.ajax({  
  14.                  type: "POST",  
  15.                  url: "dummyWebsevice.asmx/HelloToYou",  
  16.                  data: "{‘name’: ‘" + $(‘#name’).val() + "’}",  
  17.                  contentType: "application/json; charset=utf-8",  
  18.                  dataType: "json",  
  19.                  success: function(msg) {  
  20.                      AjaxSucceeded(msg);  
  21.                  },  
  22.                  error: AjaxFailed  
  23.              });  
  24.          });  
  25.      });  
  26.           function AjaxSucceeded(result) {  
  27.               alert(result.d);  
  28.           }  
  29.           function AjaxFailed(result) {  
  30.               alert(result.status + ‘ ‘ + result.statusText);  
  31.           }    
  32. </script>
  33. </head>
  34. <body>
  35. <form id="form1" runat="server">
  36. <h1> Calling ASP.NET AJAX Web Services with jQuery </h1>
  37.      Enter your name:   
  38. <input id="name" />
  39. <br />
  40. <input id="sayHelloButton" value="Say Hello"
  41. type="button" />
  42. </form>
  43. </body>
  44. </html>

Calling an ASP .NET page method

Listing 6: A dummy hello world page method

  1. [WebMethod()]  
  2. public static string sayHello()  
  3. {  
  4. return "hello ";  
  5. }   

Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carries around by an asp .NET page.

We use the same jQuery command $.ajax to call a page method, as shown in the following example.

  1. <script type="text/javascript">  
  2.       $(document).ready(function() {  
  3.           $.ajax({  
  4.               type: "POST",  
  5.               url: "pagemethod.aspx/sayHello",  
  6.               contentType: "application/json; charset=utf-8",  
  7.               data: "{}",  
  8.               dataType: "json",  
  9.               success: AjaxSucceeded,  
  10.               error: AjaxFailed  
  11.           });   
  12.     });  
  13. function AjaxSucceeded(result) {  
  14.           alert(result.d);  
  15.       }  
  16. function AjaxFailed(result) {  
  17.           alert(result.status + ‘ ‘ + result.statusText);  
  18.       }    
  19.   </script>   

For more info please visit Xun Ding’s excellent article Using jQuery with ASP .NET

jQuery in 60 secs

 

The magic dollar sign ($) and a chain of operations

In jQuery, the most powerful character / symbol is the dollar sign. A $() function normally returns a set of objects followed by a chain of operations. An example

  1. $("div.test").add("p.quote").html("a little test").fadeOut(); 

$("div.test").add("p.quote").html("a little test").fadeOut();

Think of it as a long sentence with punctuations. Indeed it is a chain of instructions to tell the browser to do the following:

  1. Get a div with class name is test;
  2. Insert a paragraph with class name is quote;
  3. Add a little text to the paragraph;
  4. Operate on the DIV using a predefined method called fadeout.

So there it is, the first two basics: $() and chainable.

jQuery Selectors

JQuery uses CSS selectors to single out one element or a group of elements, and normally we use a combination of them to target specific elements. For example:

$(‘p.note’) returns all <p> elements whose class name is note;

$(‘p#note’) returns the <p> element whose id is note;

$(‘p’) returns all <p> elements

To select a child or children, we use the right angle bracket (>), as in $(‘p>a’) (returns all of the hyper links within the <p> element);

To select element(s) with certain attributes, we use [], as in input[type=text] (returns all text input element);

To select a container of some other elements, we use has keyword, for example: $(‘p:has(a)’) (returns all <p> elements that contains an hyperlink);

jQuery also has a position-based selector for us to select elements by position, for example $(‘p:first’)

Document.Ready()

The most commonly used command in jQuery is Document.Ready(). It makes sure code is executed only when a page is fully loaded. We often place code blocks inside this Document.Ready() event. For example:

  1. $(document).ready(function(){  
  2. $("#buttonTest").click(function(event){  
  3.    alert("I am ready!");  
  4. });   
  5. }); 

$(document).ready(function(){ $("#buttonTest").click(function(event){ alert("I am ready!"); }); });

 

For more info please visit Xun Ding’s excellent article Using jQuery with ASP .NET