Sunday, July 13, 2008

3 Tips to Get jQuery Working with ASP.NET

Most of the current development at my job is ASP.NET 2.0/C#. We recently were in the final stages of completion on a project were we utilized Microsoft AJAX extensively. Albeit, the pages appeared better to the customers, but the markup was confusing and the data moving through these Update Panels to the server-side code was very large.

We recently began using the glorious JavaScript library called jQuery and are in the process of replacing the Microsoft AJAX with it. Not only has this given us lighter AJAX, but the simple control that jQuery provides makes it a lot easier to transfer code which was previously being done on the server, into little jQuery page manipulations on the client side. One modal popup that I recently converted went from around 44 KB to 300 bytes when it became visible, which is just ridiculous. One facet that I should mention is that we are also now using JSON when moving the data instead of XML; we figured if we are reducing page size to "cut out all the stops".

Below are the links to the tutorials that saved our lives, although I want a mention a few items that appear to be missing or not exactly clear:

1. ASP.NET 2.0 Web Service is missing [System.Web.Script.Services.ScriptService]
- This commented out section is included in ASP.NET 3.5 Web Services but not 2.0 ones!

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
2. Web Service calls work locally but not on IIS
- You must add the HttpPost line to your Web.Config












3. Serialize your object to JSON and then use json2.js to securely parse on the client
a. Use Microsoft AJAX library to serialize your object to JSON

using System.Web.Script.Serialization;
...
JavaScriptSerializer j = new JavaScriptSerializer();
return j.Serialize(customObject);

b. Use the json2.js parser instead of eval to protect against malicious script

var myObject = JSON.parse(myJSONtext);

Aforementioned links:
A Look Into JQuery Ajax API
3 mistakes to avoid when using jQuery with ASP.NET AJAX/
Using jQuery to Consume ASP.NET JSON Web Services/
HTTP GET and HTTP POST Are Disabled by Default