In a larger project I am having trouble getting a WCF service method to consume a JSON parameter. So I produced a smaller test case and the behaviour is echoed. If I debug t
You have not sepcified the Method parameter on web invoke. See: http://msdn.microsoft.com/en-us/library/bb472541(v=vs.90).aspx
You encode the input parameter player
of the method TotalScore
in the wrong way.
I recommend you to use JSON.stringify
function from json2.js to convert any JavaScript objects to JSON.
var myPlayer = {
Name: "Simon",
Score: 1000,
Club: {
Name: "Tigers",
Town: "Glenelg"
}
};
$.ajax({
type: "POST",
url: "/wcfservice/wcfservice.svc/json/TotalScore",
data: JSON.stringify({player:myPlayer}), // for BodyStyle equal to
// WebMessageBodyStyle.Wrapped or
// WebMessageBodyStyle.WrappedRequest
// data: JSON.stringify(myPlayer), // for no BodyStyle attribute
// or WebMessageBodyStyle.WrappedResponse
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
alert(data.TotalScoreResult); // for BodyStyle = WebMessageBodyStyle.Wrapped
// or WebMessageBodyStyle.WrappedResponse
// alert(data); // for BodyStyle = WebMessageBodyStyle.WrappedRequest
// or for no BodyStyle attributes
},
error: function (xhr, textStatus, ex) {
alert("Not Done");
}
});
If you change the BodyStyle = WebMessageBodyStyle.Wrapped
attribute of the TotalScore
method to BodyStyle = WebMessageBodyStyle.WrappedRequest
you can change the alert(data.TotalScoreResult)
in the success
handle to alert(data)
.
I got the same problems (405 methods not allowed) using WCF POST JSON data. I found on this article below
http://blog.weareon.net/calling-wcf-rest-service-from-jquery-causes-405-method-not-allowed/
Hope this help!