Passing data from a jquery ajax request to a wcf service fails deserialization? Passing data from a jquery ajax request to a wcf service fails deserialization? json json

Passing data from a jquery ajax request to a wcf service fails deserialization?


Use double quotes instead of single quotes in the JSON you are sending to the service. That is, change:

data: "{'customerId': '2'}",

to

data: '{"customerId": "2"}',

I've tested this locally and this fixes the problem.

Incidentally, I debugged this using a method I've often used when calling ASMX and WCF services using libraries other than the built-in ASP.NET tools. I called the service using the client proxy created by an asp:ScriptReference and then inspected the request being sent to the server using an HTTP sniffer (such as HttpFox for FireFox) and compared the request to the one being sent by jQuery. Then you can usually quickly see what is different (and so probably wrong) with the request. In this case, it was clear that there was a difference in the POST data being sent.


I have only ever thought that posting is essential for username and password log on functionality so this is the way I encode the JSon parameters I send to the web service...

Here is the Webservice Contract..

    [ServiceContract]    public interface ILogonService    {    [OperationContract]    [WebInvoke(      Method = "POST",      BodyStyle = WebMessageBodyStyle.WrappedRequest,      ResponseFormat = WebMessageFormat.Json    )]    string Logon(string un, string pw);    }

Here is the JQuery (Note the use of " and ' is important!)

$.ajax({  type: 'POST',  url: "/LogonService.svc/Logon",  data: '{ "un": "' + $('#un').val() + '", "pw": "' + $('#pw').val() + '"}',  contentType: "application/json; charset=utf-8",  dataType: "json",  success: function (data) {      }});


I did a function in jscript that solved the problem for sending data via POST to a WCF service ... follow the code ...

function formatJsonDataToWCFPost(d){

var t = {};var a = '{';for (var j = 0; j < d.length; j++) {    var x = d[j];    for (var i in x) {        if (x.hasOwnProperty(i)) {            var c = j + 1 == d.length ? '}' : ',';            a += ('"' + i + '":"' + x[i] + '"' + c);        }    }}return a;

}