I was supposed to present two topics at Houston Tech Fest on September 13th 2008. Unfortunately, the IKE hurricane cancelled the event. Hopefully, the event will be rescheduled in January 2009.
In this post I will try to provide the code for my presentation “A Look into the Ajax Frameworks”. Hopefully the readers will find it beneficial. The download sample is also available at the end of this post.
We are going to take a look at the three different Ajax frameworks which include Ajax.NET PRO, MS Ajax Framework and the JQuery Library.
Ajax.NET PRO Library:
Ajax.NET Pro library was one of the first Ajax libraries that I used. It is developed and maintained by Michael Schwarz. Before getting started with the Ajax.Net Pro library you need to register it in the code behind and also the web.config file.
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
</httpHandlers>
And here is the code to register the library.
private void RegisterAjaxProLibrary()
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(UsingAJAXProLibrary));
}
Let’s see how we can use the Ajax.NET PRO library to create a simple hello world application.
Here is the Ajax Method which returns the “Hello World” message to the client.
[AjaxPro.AjaxMethod]
public string GetHelloWorld()
{
return "Hello World";
}
And here is the client side code which calls the server’s method.
function getHelloWorld()
{
HoustonTechFest2008.UsingAJAXProLibrary.GetHelloWorld(getHelloWorld_callback);
}
function getHelloWorld_callback(response)
{
alert(response.value);
}
The getHelloWorld_callback function will be fired when the Ajax call is completed. The response.value will contain the result of the server side method which in this case will be “Hello World”.
That was simple! Let’s try to return a generic list of Products. The ProductRepository is responsible for returning a list of products. The AJAX.NET PRO library includes a JavaScriptSerializer class which can be used to convert an object to JSON format. Check out the usage below:
[AjaxPro.AjaxMethod]
public string GetProducts()
{
return AjaxPro.JavaScriptSerializer.Serialize(_repository.GetAll());
}
And here is the code to convert the JSON string to an object.
function getProducts()
{
HoustonTechFest2008.UsingAJAXProLibrary.GetProducts(function(response)
{
var products = eval('(' + response.value + ')');
alert(products[10].ProductName);
});
}
By converting the string to a JSON object we can iterate through the object using simple loop. This also cuts down the response string as now we are not including angle brackets and inner nesting.
MS AJAX:
Microsoft also has a framework for Ajax and it is called Microsoft AJAX Framework. I think of it as a complete framework for Ajax. This is because you can make Ajax requests just like Ajax.NET PRO framework using services. You can use Update Panel to update a portion of the page and you can also use Ajax Control Toolkit for additional Ajax controls.
Let’s see how we can use services to make Ajax requests. First we need to register the services which are performed by the ScriptManager control. Consider ScripeManager control to be the brain of the Ajax framework.
<asp:ScriptManager ID="sm1" runat="server">
<Services>
<asp:ServiceReference InlineScript="true" Path="~/AjaxService.asmx" />
</Services>
</asp:ScriptManager>
<input type="button" value="get hello world" onclick="getHelloWorld()" />
<script language="javascript" type="text/javascript">
function getHelloWorld()
{
HoustonTechFest2008.AjaxService.HelloWorld(function(response)
{
alert(response);
});
}
</script>
Now, let’s take a look at the HelloWorld server side method which is defined in the AjaxService.asmx file.
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
The MS Ajax framework also includes the JavaScriptSerializer class which can be used to convert objects to JSON format.
[WebMethod]
public string GetProducts()
{
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(_repository.GetAll());
}
MS AJAX also includes the Ajax Control Toolkit which is a collection of Ajaxified controls. Let’s take an example of the Autocomplete extender control which is used to provide auto completion features to the TextBox control.
Here is the HTML part of the code which registers the script and the Autocomplete extender control.
<asp:ScriptManager ID="sm1" runat="server" />
<asp:TextBox ID="txtProductName" runat="server" />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1"
TargetControlID="txtProductName" MinimumPrefixLength="0" ServicePath="AjaxService.asmx"
ServiceMethod="GetProductArray" runat="server">
</cc1:AutoCompleteExtender>
The ServiceMethod is the name of the method that will be called and the ServicePath is the name of the web service file.
Here is the implementation of the GetProductArray.
[WebMethod]
public string[] GetProductArray(string prefixText, int count)
{
List<Product> products = _repository.GetAll();
var matchedProducts = from p in products
where p.ProductName.ToLower().StartsWith(prefixText)
select p.ProductName;
return matchedProducts.ToArray();
}
JQuery AJAX API:
JQuery is basically a JavaScript library but it also consists of a very strong AJAX API Framework. I have blogged about the JQuery Ajax API in the following posts and articles:
On Demand Loading Using JQuery API
Using FireBug Profiler to Dig Deep into the MS AJAX and JQuery API
Performing Instant UserName Availability Check Using JQuery Ajax API
Here is the JQuery Ajax call which triggers the GetProducts method on the server side and returns the response in the JSON format.
$(document).ready(function()
{
$("#btn1").click(function()
{
// ajax call
var ul1 = document.getElementById("ul1");
$.ajax(
{
type:"POST",
data:"{}",
dataType:"json",
url:"AjaxService.asmx/GetProducts",
contentType:"application/json",
success: function(response)
{
var products = eval('(' + response.d + ')');
for(i=0;i<products.length;i++)
{
var li = document.createElement("li");
li.innerHTML = products[i].ProductName;
ul1.appendChild(li);
}
}
});
})
});
There are also some screencasts on www.screencastaday.com. Please check them out.
Hopefully, we will have the HoustonTechFest in January and you will see all of the above live in action.
[Download Sample]