Wahtever
Wahtever

Reputation: 3678

Calling AJAX-Enabled WCF Service from jQuery in asp.net

I using a Ajax-Enabled Wcf service for the first time trying to test a very basic function,

here is my service file Service.svc:

[ServiceContract(Namespace = "testService")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
public void DoWork(int id)
{
    return;
}

[OperationContract]
[WebInvoke]
[WebGet]
public string sting(int id) 
{
    string _sting = string.Format("Number is {0}" + id);
    return _sting;
}

}

and trying to use jquery to call but with this:

    $(function () {
        $.ajax({
            type: "POST",
            url: "Service.svc/sting",
            data: '{"id":"3"}',
            processData: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert("success");
            },
            error: function (msg) {
                $("#errorDiv").text(msg);
            }
        });
    });

but i always get the error as [object Object]

what am i doing wrong, thanks

Upvotes: 1

Views: 3621

Answers (1)

jocey
jocey

Reputation: 252

Two Things:

  1. You defined your web method as a [WebGet] but call it as a POST request in your Jquery Ajax method. Replace the [WebGet] with something like:

    [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json)]

  2. I'm not sure what you have in your Web.config, but you need to make sure your endpoint behaviors are defined correctly.

    If you still need help on this, if you can post your web.config file that would be helpful.

Upvotes: 2

Related Questions