Tuesday, May 5, 2009

jQuery AJAX with .Net, and No Dependencies

Goal: to have an xcopy deployable .Net 2.0 project, using AJAX and JSON and jQuery. This solution requires no web.config changes, no other binaries, no GAC stuff of any kind.

Create a page, nodep.aspx. Add jquery.js to a js folder in your project (get jquery from the net). Add an include to this file in nodep.aspx.

Add a Generic Handler file to the project, called whnodep.ashx.

Add this to nodep.aspx, anywhere you want, really.

Add this to the body

In whnodep.ashx, put this code in the ProcessRequest method, take out all code and put in this:

if (context.Request["pageAction"] == "DoSearch")

Add this procedure:

public void DoSearch(HttpContext context)
string result = "";
string sSearch = "";

sSearch = context.Request["searchterm"];

result = "{ \"letterarray\": [";
for (int i = 0; i < sSearch.Length; i++ )
result += "{ \"letter\": \"" + sSearch.Substring(i, 1) + "\" }";
if (i < sSearch.Length - 1)
result += ", ";
result += "] } ";

Done. Should work flawlessly.

JSON -- headache eliminator, part 1

I haven't used JSON very much. I like it, but I just haven't had a chance to really get down into it too deeply. However, this is the 2nd time that I've been bitten by a stupid syntax thing. The solution is on many many blogs out there, but hopefully having typed this myself, I might finally remember it.

Server side, when you are creating your object, you might concentrate on the data, and end up sending a string like this:

{ "someproperty" : "10" }

And, client side, you want to use it like this:

var o = eval(result);

Kaboom! What the hell? Why?

Because you forgot the parentheses:

var o = eval( "(" + result + ")" );

All is right with the world again.