Wcf 4.0 service call from jquery ($. Ajax)

I have a simple wcf service developed in vs2010

[ServiceContract]
public interface IService1
{

    [OperationContract]
    string GetData(int value);



    // TODO: Add your service operations here
}



public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }


}

next call works

    protected void Button1_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client p = new ServiceReference1.Service1Client();
        Label1.Text= p.GetData(5);
    }

but when i try to call it from jquery it doesn't work

    $(".test").live("click", function () {
    $.ajax({
                type: "post",
                url: "http://localhost/Service1.svc/GetData",
                data: {value:'1'},
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                processData: true,
                dataType: "json",       
                success: function(d) {  
                alert(d);                                            
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert(xhr.status);
                         alert(thrownError.toString());
                    }
        });

can someone help me because he gives me sleepless nights. thanks in advance.

+3
source share
2 answers

Check the JSON data type passed over the wire (using Fiddler2 or the developer tools in the browser of your choice). I suspect JSON passes "1" as a string instead of an integer.

It looks like the problem is in the data argument:

data: {value:'1'},

It should not have single quotes around it. The service is trying to solve a method with a variable "value" with a string type. Do this instead:

data: {value:1},

.

0

,

$(".test").live("click", function () {
$.ajax({
            type: "post",
            url: "http://localhost/Service1.svc/GetData",
            data: "{'value':1}",
            contentType: "application/json; charset=utf-8",
            timeout: 10000,
            processData: true,
            dataType: "json",       
            success: function(d) {  
            alert(d);                                            
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                     alert(thrownError.toString());
                }
    });
0

Source: https://habr.com/ru/post/1790399/


All Articles