Thursday, December 8, 2011

Generic Handlers in .NET and AJAX

If you've ever come across an instance where you don't want to use UpdatePanels but you need some ajax functionality (i.e. you need to do ajax manually), generic handlers are the way to go. I could probably write an entire post on why UpdatePanels are not always a great idea but here is one alternative.

To start with, create a generic handler. This should be easy enough. In the ProcessRequest(HttpContext context) method, you want to grab your parameters from the context. Here's an example:

string url = context.Request.QueryString["url"];

Once you've done that, take your parameters, do whatever functionality you need, and the .ashx should return the value via context.Response.Write().

On the client side, use the following javascript to read the response:

function createXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
alert("XMLHttpRequest not supported");
return null;
}

var xmlHttpReq= createXMLHttpRequest();
xmlHttpReq.open("GET", "your.ashx?v1=1&v2=2&etc", false);
xmlHttpReq.send(null);
var yourJSString = xmlHttpReq.responseText;

Then, take that response value and use JQuery or javascript to make whatever change you need on the front end. It's that simple! Now you are making AJAX calls from scratch, and you can feel like you know something.

No comments:

Post a Comment