What a pain! I'm trying to call a web service from JavaScript but I just can't seem to find the magic sauce needed to make it work.
My code looks something like this:
JavaScript:
$.ajax({
url: "/Services/CompanyContactServices.asmx/AddContact",
type: 'POST',
contentType: "application/json",
dataType: "json",
data: {
companyId: 3725, firstName: firstName, lastName: lastName, email: email
},
success: function (data) {
alert('Success!');
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
Web Service (asmx.cs):
[WebService(Namespace = CompanyListServices.XmlnsNamespace)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class CompanyContactServices : System.Web.Services.WebService
{
public const string XmlnsNamespace = "mynamespace";
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string AddContact(int companyId, string firstName, string lastName, string email)
{
return new JavaScriptSerializer().Serialize(0);
}
}
A breakpoint at the start of my AddContact
method is never reached.
The error
handler for my ajax()
call contains the following error message in jqXHR
:
{ Message":"Invalid JSON primitive: companyId.", "StackTrace":"at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input) at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer) at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}"
Chrome reports the following network data:
Request URL:.../Services/CompanyContactServices.asmx/AddContact
Request Method:POST
Status Code:500 Internal Server Error
Can anyone see what I'm missing?