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")
DoSearch(context);

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 += "] } ";
context.Response.Write(result);
}

Done. Should work flawlessly.

No comments:

Post a Comment