To get an ASP.NET SOAP Web Service (asmx) working with jQuery, you first have to add a ScriptServiceAttribute
(found in System.Web.Script.Services
) to the service itself:
[ScriptService] // <--- here
public class MyWebService : WebService
{
[WebMethod]
public int Sum(int x, int y)
{
return x + y;
}
}
If the project wasn't created as an ASP.NET AJAX project, you may need to modify your web.config
with the following:
<configuration>
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false"
type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpHandlers>
</system.web>
</configuration>
(Note - update the System.Web.Extensions
assembly reference with the appropriate version - this is for ASP.NET AJAX 1.0, which is not current. I don't have the info for 2.0, otherwise I'd post it.)
The jQuery code can be written like so:
$.ajax({
type: "POST",
url: "/MyWebService.asmx/Sum",
data: "{x: 2, y: 5}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#Result").html(msg);
}
});
Note that this will break any clients that rely on the XML service - I'm assuming for the sake of this answer that the only consumer of the web service will be web sites using jQuery or at least JavaScript. If you need to support both scenarios then you will need to create two web services.