Ajaxafy your .Net application with JQuery

Category : Ajax

Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. -wikipedia

There are many techniques for using Ajax in .Net. You can use the ASP.Net ajax library, third party components or even Client Side Callbacks. However, sometimes you just need to simply call your server side code and you don’t want to add-in any more frameworks. If you want to use JQuery here is my recommended approach for achieving this goal.

This solution consists of:

  • JQuery function
  • HttpHandler
  • xslt file for styling

Prerequisites:

  • Visual Studio solution (I am using Visual Studio 2010 with a c# project. But, this will work with other versions of Visual Studio and other code bases)
  • ASP.Net web application project. Technically this will work with other web types, this walk through just uses a web application project.
  • Jquery referenced in your header:This is important, please don’t miss this step. I am using version 1.3.2 –
    
    <script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    

Step 1 (Create the JQuery function):

Before we create the JQuery function we have to put a button to run our example and an html tag on our webpage that we are going to fill in with the html returned from the Ajax call. So, place similar html on your page such as:


<input type="button" value="Test" onclick="LoadAjax('test', 'red', 'green')" /><div id="test">

The JQuery function simply passes parameters (in the data variable) to the httphandler (ashx) so that the server-side can process the code. Then it sets the html of the container id to the html returned.


        function LoadAjax(containerid, color, backgroundcolor) {
             $.ajax({
                 type: "GET",
                 url: "Handler1.ashx",
                 data: "color=" + color + "&backgroundcolor=" + backgroundcolor,
                 success: function (responseText) {
                     $('#' + containerid).html(responseText);
                 }
             });
         }

*note: Please be careful with the url variable. It must point to where you want to locate your ashx httphandler. In my case, it is at the same level as the webpage that is running the jquery function.

Another thing to note with this function is the simplicity of the “success” in the JQuery ajax call. All we do is render the html received from the server side into the container id’s html element. That means the server side must render our html for us.

Lastly, note the “data” variable. This passes the Request parameters to the server side code.

Step 2 (Create the HttpHandler):

1. Create an “Generic Handler” file (i.e.: httphandler) in your Visual Studio Solution. For this examples case we are creating a file called Handler1.ashx at the same level as our webpage.

Notice the “ProcessRequest” method that is built for you. Technically, you can just build your html in this, on the server-side. Try it – build/debug your application, click the test button and “Hello World” should show up.

That’s basically it, but it’s not a great example. You’d have to build all your html on the server in strings. That might work for you, but that can be hard with complicated html. So, lets style this a little and create some html through an xslt file. To do this we need the httphandler to tell us the xslt file to use and to pass xml into the xslt file.

2. Edit your httphandler. We are just going to build xml based off the parameters we passed in and format the xml with xslt.


 public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";

            string color = context.Request["color"];
            string backgroundColor = context.Request["backgroundcolor"];

            string xml = GetXml(color, backgroundColor, "Hello World");

            context.Response.Write(Transform(xml,
                              context.Server.MapPath("~/Test.xslt")));
        }

        public static string GetXml(string color,
                                 string backgroundColor,
                                 string value)
        {
            StringWriter stringWriter = new StringWriter();
            XmlTextWriter xmltextWriter = new XmlTextWriter(stringWriter);

            xmltextWriter.WriteStartDocument();
            xmltextWriter.WriteStartElement("TestXML");
            xmltextWriter.WriteStartElement("TestSettings");

            xmltextWriter.WriteElementString("Style",
                      "color:" + color + ";background-color:" + backgroundColor);
            xmltextWriter.WriteElementString("Value", value);

            xmltextWriter.WriteEndElement();
            xmltextWriter.WriteEndElement();
            xmltextWriter.WriteEndDocument();

            return stringWriter.ToString();
        }

        public static string Transform(string xml, string xsl)
        {
            XslCompiledTransform transform;
            XPathDocument xpd;
            StringWriter sw;
            XmlTextWriter writer;

            xpd = new XPathDocument(new StringReader(xml));
            sw = new StringWriter();
            transform = new XslCompiledTransform();
            transform.Load(xsl);
            writer = new XmlTextWriter(sw);
            transform.Transform(xpd, null, writer);

            return sw.ToString();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

In the code above the “Transform” method is a simple helper method that associates xml with the xslt. The “GetXml” method simply builds the xml out based on the parameters passed in. The “ProcessRequest” method gets our parameters from the Request object, calls the methods to build the xml and sends the html that is built back to the Response object.

Step 3 (Create the XSLT):

The last thing you need to do is build the xslt that will build your html for you based on the information in the xml passed in. Just create an xslt file called “Test.xslt” and put the following xslt in it:


<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" />

<xsl:template match="/TestXML/TestSettings">
<xsl:element name="div">
<xsl:attribute name="style">
<xsl:value-of select="Style"/>
</xsl:attribute>
<xsl:value-of select="Value"/>
</xsl:element>
</xsl:template>

</xsl:stylesheet>

Now you should be able to run your project, click the button and the HelloWorld should have a green background and red font (exactly what the client side told you to build). Now that you see how to call server side code from a JQuery call, the possibilities are endless for what you can accomplish.

Client Side Callbacks (AJAX technique)

8

Category : Ajax

After a few SharePoint posts I decided I should post some interesting things in .net. Client Side Callbacks have been something I have been using for years and I have always wondered why they don’t get more press. Client Side Callbacks are basically .nets way of wrapping the XmlHttpRequest object. As any good web developer knows (who implements Ajax) – all Ajax is is a buzzword for Asynchronous javascript and xml. However, all “real” Ajax technologies use the XmlHttpRequest to asynchrounously call the server. In fact, one of my big pet-pieves is when people use the word Ajax incorrectly (however, that is for another discussion).

So, to implement Ajax you don’t really need any of these “toolkits” like Ajax.net (formerly Atlas) or Ajax pro. These are just “toolkits” to help you implement Ajax technologies. I have found that these toolkits can produce bloatted javascript and can actually slow down an application if not used correctly. Thus, whenever I have a simple Ajax need I try to use .nets Client Side Callbacks instead of an Ajax toolkit. With that said, there are good uses for these toolkits if your business requirements meet some of their features. It is up to a good architect to determine when these should be used.

The Client Side Callback feature is available in .net 1.1 and 2.0 forward. However, the version in 1.1 is a little lacking, so I will concentrate this blog on the 2.0 version forward.

The simplest need for Ajax is to call the server asynchrounously, allow it to process information, make a call back to the client and allow the client to show the information on the screen (using javascript). The following example will show how to call the server (to get the datetime from the server) and have that datetime show up on the screen without any postbacks.

  1. First create your website and go to the code behind of your default.aspx.
  2. Implement the System.Web.UI.ICallbackEventHandler on the class.
  3. This interface will produce two methods (RaiseCallbackEvent and GetCallbackResult). Make sure both of these methods get implemented.
  4. The RaiseCallbackEvent method will be the first method called when the Callback starts. This method takes in an argument, which you can store as a member variable on your class to use in the GetCallbackResult. The GetCallbackResult method is the method in which you will build the arguments to pass back to the client side javascript.
  5. Implement the code within the RaiseCallbackEvent and GetCallbackResult methods:
  6. 
    private string _argument = string.Empty;
    
    /// The RasieCallbackEvent is the first place to receive the callback from the client's browswer when 'CallServer'
    /// is triggered.parameter passed from the Javascript's call 'CallServer'
    public void RaiseCallbackEvent(string eventArgument)
    {
    //store the argument in a local variable so we can use it in the "GetCallbackResult" method
    //later on if necessary.
    _argument = eventArgument;
    }
    
    /// The GetCallbackResult method is the second call triggered by the 'CallServer()'
    /// on the client side. This is the place to prepare a string that can be placed as
    /// html on the page.
    public string GetCallbackResult()
    {
    //run the code to add the html to the javascript callback method
    if (_argument == "getServerTimeUserControl")
    {
    //return the html
    return System.DateTime.Now.ToString();
    }
    else
    {
    return string.Empty;
    }
    }
    
  7. Next implement the page_load method like this:
  8. 
    protected void Page_Load(object sender, EventArgs e)
    {
    //only need to register once, so don't register when a callback is being performed
    if (!Page.IsCallback)
    {
    //Register the Ajax client script to the client's broswer
    string eventReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context");
    string callbackScript = "function CallServer(arg, context)" + "{ " + eventReference + "} ;";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
    }
    }
    
  9. The page_load is registering client side scripts, so next we have to go to the default.aspx webpage and build those javascript methods:
  10. 
    function GetServerTime(argument)
    {
    //Send the request to server
    CallServer(argument, "");
    }
    
    function ReceiveServerData(argument)
    {
    document.getElementById("serverTimeUserControlArea").innerHTML = argument;
    }
    
    The ReceiveServerData is the javascript method we registerd in the page_load of the code behind, so that is the method that the client side callback will eventually write back to. The GetServerTime is our javascript method we are going to call to kick off the client side callback functionality.
  11. Build the html. This will just consist of a button to start the client side callback and a div to fill in when the information is retrieved from the server:
  12. <input type=”button” onclick=”javascript:GetServerTime(‘getServerTimeUserControl’);” id=”Button1″ />
    <div runat=”server” id=”serverTimeUserControlArea”></div>

    Thats it!
    It is that easy to implement your own, custom, Ajax solution in .net. You don’t need to implement any third party Ajax solutions to get this to work. Now that you have seen the simplest example you can use your imagination to do more complicated things. For example: You could load up user controls and render their html out to the client side with these techniques. Just be careful because the post-back never occurs, which means certain server side things never happen. You will have to play around with the technique to see what you get.

    Attached is my default.aspx and default.aspx.cs files from the example:
    Default page
    default page code behind