6

I am trying to do something that I thought would be simple. I need to create a WCF service that I can post to via JQuery. I have an operation in my WCF service that is defined as follows:

[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json)]
public string SendMessage(string message, int urgency)
{
  try
  {
    // Do stuff
    return "1";  // 1 represents success
  }
  catch (Exception)
  {
    return "0";
  }
}

I then try to access this operation from an ASP.NET page via JQuery. My JQuery code to access this operation looks like the following:

function sendMessage(message) {
  $.ajax({
    url: "/resources/services/myService.svc/SendMessage",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: ({ message: message, urgency: '1' }),
    dataType: "json",
    success: function (data) {
      alert("here!");
    },
    error: function (req, msg, obj) {
      alert("error: " + req.responseText);
    }
  });
}

When I execute this script, the error handler is tripped. In it, I receive an error that says:

"Encountered unexpected character 'c'."

This message is included with a long stack trace. My question is, what am I doing wrong? I have received other posts such as this one (How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?) without any luck. How do I get this basic interaction working?

Thank you!

Community
  • 1
  • 1
Villager
  • 6,569
  • 22
  • 65
  • 87
  • 1
    I think you are passing parameters incorrectly. Have a look at the following page: [3 mistakes to avoid when using jQuery with ASP.NET AJAX](http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/) – Giorgi Mar 20 '10 at 19:29
  • That site is unreachable for me at the moment - what did it say? – Rowland Shaw Jun 27 '12 at 11:40

1 Answers1

3

I think you have to stringify your json-data in the request. More info here. You might also want to parse incoming response data, since it will be stringified in return. A common library suited for the task kan be found here.

Eg.: data: '{ message: "message", urgency: "1" }',

maets
  • 750
  • 6
  • 18
  • I had this same problem and turns out you should not pass the data in the $.ajax method as a json object but rather as a string.. maets's answer is spot on. – Pankaj Kumar Sep 05 '12 at 12:46