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:
- <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:
- <script type="text/html" id="TemplateResultsTable">
- {#template MAIN}
- <table cellpadding="10" cellspacing="0">
- <tr>
- <th>Artist</th>
- <th>Company</th>
- <th>Title</th>
- <th>Price</th>
- </tr>
- {#foreach $T.d as CD}
- {#include ROW root=$T.CD}
- {#/for}
- </table>
- {#/template MAIN}
- {#template ROW}
- <tr class="{#cycle values=['','evenRow']}">
- <td>{$T.Artist}</td>
- <td>{$T.Company}</td>
- <td>{$T.Title}</td>
- <td>{$T.Price}</td>
- </tr>
- {#/template ROW}
- </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.
- $(document).ready(function() {
- $.ajax({
- type: "POST",
- url: "CDCatalog.asmx/GetCDCatalog",
- data: "{}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(msg) {
- //instantiate a template with data
- ApplyTemplate(msg);
- }
- });
- });
- function ApplyTemplate(msg) {
- $(‘#Container’).setTemplate($("#TemplateResultsTable").html());
- $(‘#Container’).processTemplate(msg);
- }
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
- [WebService(Namespace = "http://tempuri.org/")]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [System.Web.Script.Services.ScriptService]
- public class dummyWebservice : System.Web.Services.WebService
- {
- [WebMethod()]
- public string HelloToYou(string name)
- {
- return "Hello " + name;
- }
- [WebMethod()]
- public string sayHello()
- {
- return "hello ";
- }
- }
For example, we can call a specific web method in a web service as such.
Listing 4: JQuery .ajax command
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "WebService.asmx/WebMethodName",
- data: "{}",
- dataType: "json"
- });
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
- <%@ Page Language="C#" %>
- <%@ Import Namespace="System.Web.Services" %>
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html >
- <head id="Head1" runat="server">
- <title>ASP.NET AJAX Web Services: Web Service Sample Page</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jQuery/1.2.6/jQuery.min.js">
- </script>
- <script type="text/javascript">
- $(document).ready(function() {
- $("#sayHelloButton").click(function(event){
- $.ajax({
- type: "POST",
- url: "dummyWebsevice.asmx/HelloToYou",
- data: "{‘name’: ‘" + $(‘#name’).val() + "’}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(msg) {
- AjaxSucceeded(msg);
- },
- error: AjaxFailed
- });
- });
- });
- function AjaxSucceeded(result) {
- alert(result.d);
- }
- function AjaxFailed(result) {
- alert(result.status + ‘ ‘ + result.statusText);
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <h1> Calling ASP.NET AJAX Web Services with jQuery </h1>
- Enter your name:
- <input id="name" />
- <br />
- <input id="sayHelloButton" value="Say Hello"
- type="button" />
- </form>
- </body>
- </html>
Calling an ASP .NET page method
Listing 6: A dummy hello world page method
- [WebMethod()]
- public static string sayHello()
- {
- return "hello ";
- }
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.
- <script type="text/javascript">
- $(document).ready(function() {
- $.ajax({
- type: "POST",
- url: "pagemethod.aspx/sayHello",
- contentType: "application/json; charset=utf-8",
- data: "{}",
- dataType: "json",
- success: AjaxSucceeded,
- error: AjaxFailed
- });
- });
- function AjaxSucceeded(result) {
- alert(result.d);
- }
- function AjaxFailed(result) {
- alert(result.status + ‘ ‘ + result.statusText);
- }
- </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
- $("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:
- Get a div with class name is test;
- Insert a paragraph with class name is quote;
- Add a little text to the paragraph;
- 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>elementsTo 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 thisDocument.Ready()event. For example:
- $(document).ready(function(){
- $("#buttonTest").click(function(event){
- alert("I am ready!");
- });
- });
$(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
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
Samuraitype that was defined in theWarriorModule. - (1) The kernel asks the
Samurai‘sTransientBehaviorto resolve an instance. - (1) The Samurai’s
TransientBehaviorasks the binding’s provider to create a new instance. - (2) The Samurai’s
StandardProviderasks the kernel to resolve an instance ofIWeapon. - (2) The kernel resolves the binding from
IWeapontoSwordthat was defined in theWarriorModule. - (2) The kernel asks the
Sword‘sTransientBehaviorto resolve an instance. - (2) The
Sword‘sTransientBehaviorasks the binding’s provider to create a new instance. - (2) The
Sword‘sStandardProvidercalls theSword‘s parameterless constructor. - (2) The kernel returns the newly-created instance of
Sword. - (1) The
Samurai‘sStandardProvidercalls theSamurai‘s injection constructor, passing it the instance ofSwordas an argument. - (1) The kernel returns the newly-created instance of
Samuraito the site of the method call inMain().
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/
