Sunday, November 14, 2010

AJAX with jQuery in ASP.Net

There are already a whole bunch of blogs out there on this subject by people much more qualified for the task. I'm just trying to compile my own efforts to preform an AJAX call on a ASP.Net page to a method in the page's code-behind in one place. There are enough quirks for me to know I'd have to look things up in the future so might as well just put it all in one place and make it available for anyone else who might want this info.

Microsoft's CDN link for the jQuery library (current release at the time of writing)

Reference it in the head of your page like this:

With jQuery, when the page is ready for manipulation (loaded except for images) add a click event handler to a button with id="btnServerCall"
$(document).ready(function () {
$("#btnServerCall").click(function (event) {
//This prevents the event from propagating further
event.preventDefault();

//TODO: Event handler code goes here
});
});

Now lets setup the server side method that we want to call. There is a requirement that the method be static (C#) or shared (VB) and marked with the WebMethod attribute. This prevents you from working with anything else that is outside of the scope of the method but this isn't anything new to async stuff. Also make sure you have System.Web.Services referenced as this method will be called just like a web service by jQuery. My method looks like this:
[WebMethod()]
public static string ServerGreeting(string userName)
{
return ("Hello " + userName).Trim() +
"! The current server time is: " +
DateTime.Now.ToString();
}

Now for the jQuery AJAX call which will be the event handler code added to the first chunk of code
$.ajax({
type: "POST",
url: "jQueryTest.aspx/ServerGreeting",
data: "{'userName': '" + $('#txbName').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function(result) {
alert(result.status + ' ' + result.statusText);
}
});

If you're wondering what that business with the success and error parameters is all about, those are anonymous methods that are going to be called on the completion of the call to the server and depending on the success or failure of it.

That's pretty much it. I went heavy on the code and light on the explanation as this is really meant to be a reference and not a tutorial.

I got almost all of this from http://dotnetslackers.com/articles/ajax/Using-jQuery-with-ASP-NET.aspx which covers way more material then I did here and gives a lot more explanation. I just extracted out what I needed to preform an AJAX call.

If you want to read more about jQuery, http://jquery.com/ is the the place to go.

No comments:

Post a Comment