Friday 3 September 2010

jQuery with ASP.NET Web Service

Had a very productive day today hooking up an HTML web page with the jQuery library to an ASP.NET web service. I've written previously about my research into this and while the WCF RESTful stuff looked good I wasn't convinced it was the best way forward to this. We've decided to use a sickness absence report as a trial for developing some skills in Javascript development and today I was looking for a better way to expose web service methods that jQuery could easily communicate with.

After several hours of searching and some dead ends I stumbled across this article http://www.dotnetcurry.com/ShowArticle.aspx?ID=320&AspxAutoDetectCookieSupport=1 that finally showed me how to do all the things I have been reading about. The standard ASP.NET web service gets a few additions to it (such as System.Web.Script.Services.ScriptService / ScriptMethod) and you can tell the individual ScriptMethod to return data as JSON. That's great because the numerous jQuery AJAX examples all deal with JSON instead of XML. The article also shows you how to return a List of data from VB.NET (something I had never done before - I have always used DataSet / DataTable) which allows you to create a custom List with a number of attributes and then add as many items to this List as you like. The list gets populated with data from the SQL result set.

You can then write what is now becoming a pretty standard jQuery AJAX function, get a result set object, loop through it with a FOR loop and write the output into an HTML table, which then gets displayed in a div on the page (that's another thing I love about jQuery; you can actually modify whole divs).

There are plenty of examples in C# on the web but this is the first complete working example I found in VB.NET. Check it out!

No comments: