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

Ninject Cheat Sheet

image

Constructor Injection

class Samurai {
  private readonly IWeapon _weapon;

[Inject] // limit to 1 constructor ONLY, use Property Injection if you need more than 1 however the order is non-deterministic. public Samurai(IWeapon weapon) { _weapon = weapon; }

public void Attack(string target) { _weapon.Hit(target); } }

 

Activation Process

For instance,

//note: type bindings are collected into groups called modules.
//You can create as many modules as you'd like, and pass them all to the kernel's constructor. 
//e.g. IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...);
class WarriorModule : StandardModule {
  public override Load() {
       //note: Module isn’t limited to a boring, static collection of bindings. You can always do more creative things like conditional bindings & contextual bindings.
    Bind<IWeapon>().To<Sword>(); // type binding
    Bind<Samurai>().ToSelf(); // self-bound, only allow in concrete type. 
  }
}
class Program {
  public static void Main() {
    IKernel kernel = new StandardKernel(new WarriorModule());
    Samurai warrior = kernel.Get<Samurai>();
    warrior.Attack("the evildoers");
  }
}

 

The activation process for the Samurai type is as follows. The number to the left indicates the depth at which the activation is occurring, and some steps have been left out for clarity:

  • (1) The kernel resolves the self-binding for the Samurai type that was defined in the WarriorModule.
  • (1) The kernel asks the Samurai‘s TransientBehavior to resolve an instance.
  • (1) The Samurai’s TransientBehavior asks the binding’s provider to create a new instance.
  • (2) The Samurai’s StandardProvider asks the kernel to resolve an instance of IWeapon.
  • (2) The kernel resolves the binding from IWeapon to Sword that was defined in the WarriorModule.
  • (2) The kernel asks the Sword‘s TransientBehavior to resolve an instance.
  • (2) The Sword‘s TransientBehavior asks the binding’s provider to create a new instance.
  • (2) The Sword‘s StandardProvider calls the Sword‘s parameterless constructor.
  • (2) The kernel returns the newly-created instance of Sword.
  • (1) The Samurai‘s StandardProvider calls the Samurai‘s injection constructor, passing it the instance of Sword as an argument.
  • (1) The kernel returns the newly-created instance of Samurai to the site of the method call in Main().

 

Activation Behavior

There are four built-in behaviors available in Ninject. Attribute is class level:

TransientBehavior [Transient]

A new instance of the type will be created each time one is requested.

SingletonBehavior [Singleton]

Only a single instance of the type will be created, and the same instance will be returned for each subsequent request.

OnePerThreadBehavior [OnePerThread]

One instance of the type will be created per thread.

OnePerRequestBehavior [OnePerRequest]

One instance of the type will be created per web request, and will be destroyed when the request ends.

Instead of relying on attributes, you can also define the behavior when you declare the binding:

Bind<Shogun>().ToSelf().Using<SingletonBehavior>();

Contextual Binding

For instance,
Bind<IWeapon>().To<Sword>();
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Target.HasAttribute<RangeAttribute>()); // using attrib
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Tag == "range"); // using attrib: [Inject, Tag("range")]
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Service.Name.StartsWith(“Foo”); // using convention
Bind<IWeapon>().To<Shuriken>().Only(When.Context.Target.Name.BeginsWith(“Remote”); // using convention
// note: IWeapon is the “Service Type”(generally an interface of abstract type) 
// while Sword/Shuriken are “Impl/Target Type”

 

For a complete tutorial visit http://dojo.ninject.org/