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.





