Dean
Dean

Reputation: 372

jQuery AJAX POST to ASMX web service results in "Cannot convert object of type System.String to System.Collections.Generic.IDictionary"

I have an ASMX web service set up as follows as a test:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public bool Test (string id)
{
    if (id != null)
    {
        return true;
    }
    else
        return false;
}

From jQuery I then wasn't to call that web method and pass in a parameter "id". So I use:

$.ajax({
    var data = JSON.stringify("id: 123");
    data: data,
    dataType: "json",
    url: url
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (result) {},
    error: function (xmlHttpRequest, textStatus, errorThrown) {
          console.log(xmlHttpRequest.responseText);
          console.log(textStatus);
          console.log(errorThrown);
    }       
});

I have used JSON.stringify to make sure the JSON is correct. However when I run the above I get the following 500 Internal Server error back:

{"Message":"Cannot convert object of type \u0027System.String\u0027 to type \u0027System.Collections.Generic.IDictionary`2[System.String,System.Object]\u0027","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"} VM12798:89 error

It looks to me like this error is occurring once the request as been received via the server. I'm not sure however, why its trying to turn the string into an IDictonary?

The above code seems simplistic. Am I setting up the JSON wrong? If I console.log data it returns:

"id: 123"

Is ASMX expecting something different?

Upvotes: 0

Views: 2307

Answers (1)

dana
dana

Reputation: 18125

You are declaring var data inside a JSON object. Just set the data property directly.

Also, you are using JSON.stringify incorrectly. It should be used to convert a JavaScript object into a JSON string.

See updated code below:

$.ajax({
        data: JSON.stringify({id: "123"}),
        dataType: "json",
        url: url
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (result) {},
        error: function (xmlHttpRequest, textStatus, errorThrown) {
              console.log(xmlHttpRequest.responseText);
              console.log(textStatus);
              console.log(errorThrown);
        }                   
});

Upvotes: 1

Related Questions