ASP.NET Performance: Fast AJAX, Faster AJAX

 Alik Levin    AJAX improves significantly both user experience and performance. It can be further improved by using down level capabilities that .Net framework offers. Specifically, consuming Web Services and WCF directly from client script. The best part is that ASP.NET AJAX comes with built in libraries - server and client - that make coding fun while significantly improving the web application's performance.

Customer Case Study

The customer was using hand crafted XmlHttp requests from client scripts requesting the data from ASPX pages. While the goal was achieved - the amount of information sent to the server was minimal and the user interface was responsive - the coding was not really fun. Also, since the requests were sent to regular ASPX pages the whole ASPX pipeline was executing unnecessarily utilizing CPU for nothing. The customer did not want to use Update Panel control. Although it boosts coding productivity, it also adds some burden on the network. Network utilization should have been kept to the minimum.

Analysis

After quick research I found two great resources that directed me to the solution that would satisfy both requirements:

  1. Coding productivity.
  2. Minimum of data in transit on the wire.

The first one is from Chris Hay  - remix08 UK ASP.NET Front End Performance Slides and the other one is from Jeff Prosise - Power ASP.NET AJAX Programming. They both outline the usage of Script-Callable Web Services. There are three simple steps to follow:

  • Declare your Web Service as Script-Callable by adding class level attribute:
 [System.Web.Script.Services.ScriptService]
public class AJAXCallableWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string HelloWorld(string name)
    {
        return "Hello, " + name;
    }
}

  • Declare service reference inside the ScriptManager:
 <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference InlineScript="true" Path="~/AJAXCallableWebService.asmx" />
    </Services>
</asp:ScriptManager>

  • Call a Web Service from the client script:
 <script type="text/javascript" language="javascript">
function callAjax()
{
    var text = document.getElementById("Text1").value
    
    AJAXCallsWebService.AJAXCallableWebService.HelloWorld(text,onSuccess);
}
function onSuccess(result)
{
    document.getElementById("result").innerText = result;
}
</script>

     <span id="result"></span>
    <input id="Button1" type="button" value="button" onclick="callAjax()" />
    <input id="Text1" type="text" />

Sample Visual Studio Solution

Grab the sample solution implemented using Visual Studio 2008 form my SkyDrive here:

submit to reddit

This template is made with PracticeThis.com plugin for Windows Live Writer