Calling ASP.NET Web Services from jQuery

I prefer compiling our web-projects to ASP.NET 2.0 rather than 3.5 basically because of all that stuff that Visual Studio adds to the "Web.config" file. And the "Web.config" is often edited by our end-users, who might find it confusing to make their way through all these "configSections", "assemblies" and "httpHandlers" that look quite scary.

With the latest project we are working on (a CRM and contact management application) we decided to finally benefit from the MS AJAX framework that is built in to the .NET Framework 3.5.

But to optimize our code and keep it lightweight and fast, we have decided to use jQuery where possible, avoiding the bulky and clumsy MS AJAX is javascript.

So - how do you use jQuery to call a JSON ASP.NET web-service? Here is it. The code is self-explaining:

WebService code:


1. [WebService(Namespace = "http://mynamespace.org/")]
2. //the next line is important
3. [System.Web.Script.Services.ScriptService]
4. public class MyWebService : System.Web.Services.WebService
5. {
6. [WebMethod]
7. public string HelloWorld(int a, string b)
8. {
9. return "Hello World";
10. }
11. }

[WebService(Namespace = "http://mynamespace.org/")]

//the next line is important

[System.Web.Script.Services.ScriptService]
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld(int a, string b)
{
return "Hello World";
}
}


Now the client-side code. Note the JSON-serialized parameters passed with the "data" property:


1. $.ajax({

2. type: "POST",

3. url: "MyWebService.asmx/HelloWorld",

4. data: {a:1,b:"test"},

5. contentType: "application/json; charset=utf-8",

6. dataType: "json",

7. success: function(msg) {

8. alert(msg.d);

9. }

10. });


If you have better solution, just tell me !

0 comments: