简体   繁体   中英

Send data to wcf webservice from jquery

I am trying to send a json string to a wcf webservice from a html page using jquery. But it is giving error and not returning the desired result. The html page is showing error. How to debug a service to see if the page is actually calling the webservice. Please help.

IService1.cs

public interface IService1
{

    [OperationContract]
    string GetData(int value);

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: Add your service operations here
}


// Use a data contract as illustrated in the sample below to add composite types to service operations.
[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

Service1.svc.cs

namespace WcfService2
{

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

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}
}

jquery code

var markers = [{ "value": "128" }];

    $.ajax({
        type: "POST",
        async: false,
        data: JSON.stringify({ Markers: markers }),
        url: "http://localhost:13008/Service1.svc/GetData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",          
        success: function (data) {
            alert(data);
        },
        error: function () {
            alert("Error");
        }
    });

Remove the data part in the AJAX call and pass the parameter in the url. Like this: http://localhost:13008/service1.svc/GetData?value=128

I think you need to mention webHttpBinding for configuring endpoint for restful services. By default it might be using basicHttpBinding when u start a service in visual studio.

You also need to add attribute [WebInvoke(Method="GET", ResponseFormat=WebMessageFormat.Json,uriTemplate="/json/{id}")] not checked in ide. But something similar to it is what you need to add.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM