I have a WCF Service (called “myservice.svc”) that takes a message from a user and saves it to the database. It returns a response to the user in the form of a number. This operation looks like this:
[OperationContract]
[WebGet]
public string SubmitMessage(string message)
{
try
{
// SAVE TO DATABASE
return "1";
}
catch (Exception ex)
{
return "0";
}
}
I want to call this operation from some JQuery. I’m using the approach shown here:
$.getJSON(
"/services/myService.svc",
{message:"some text"},
function (data) {
alert("success");
}
);
Oddly, the “success” alert is never displayed. In addition, I have set a breakpoint in my WCF service and it is never being tripped. What am I doing wrong?
Thank you
That
WebGetshouldn’t be there, and you shouldn’t be using the jQuerygetJSONfunction. This method modifies the database; it is aPOSTmethod, notGET.See this page for an example of creating a
POSTmethod. Mainly it involves adding these headers to the method:You also need to make sure that you make the call correctly from jQuery, which includes setting the
contentTypeand other fields; the way you’re making the call actually isn’t valid, you’re just passing raw text to the method, not a valid query string or valid JSON.Also, you’re using the wrong URL; you don’t want to be posting to the endpoint, you need to post to the specific method, you have to append that to the URL. Again, the linked page should help explain all of this.
Here’s an example of a correct jQuery Ajax post: