Tuesday, December 20, 2011

calling asp.net (asmx) web service from jquery .ajax()

There is lot of information out there on this very topic but I got errors while implementing it and finally fixed it. So I wanted to post my findings with example. 1) When you create .Net ASMX Web Service, it will look like following: 

 [WebService] //(Namespace = "http://WebService/") 
 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] 

 public class WebService : System.Web.Services.WebService 
  public string HelloWorld() 
 return "Hello World"; 

Here the attribute in bold is very important. That indicates that this service can be called from the Javascript+ajax methods. 

You may see [ScriptMethod(ResponseFormat = ResponseFormat.Json)] attribute used for the Web-methods but this may not be necessary. At least when I ran the example I could run it successfully with and and without this attribute. Because the response format of the method will be determined based on the content-type used by the caller. Hence its important to set the 'content-type' from caller as below:

        type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: 'http://localhost:1197/WebService.asmx/HelloWorld',
            dataType: "json",
            data: "{}",
            success: function(msg) {
            error: function(xhr, desc, ex) {

I was trying above example w/o 'contentType' and error function was called with 'parser error'. So having contentType in above is really important. 

Passing "{}" for data is not that important when your functions do not have any parameters. I could successfully call function w/o it, but if you get errors, you can try that.

Same for dataType: "json" - I commented it out and returned value was still interpreted as "json". I believe - again this is due to the contentType.

No comments:

Post a Comment