WCF方面的Passed参数为null

时间:2010-02-01 06:08:32

标签: jquery wcf json

我使用Jquery在WCF端调用一个简单的方法。

$.ajax({
         type: "POST",
         url: "MyService.svc/TestJSON",
         data:'{"BikeId":"2"}',
         //data: '{"BikeId":"'+ id + '"}',                 
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function(msg) {
             alert(msg);
         },
         error: GetFailedMessage
     });
     function GetFailedMessage(msg) {
         alert('Error message. ' + msg.status + ' ' + msg.statusText);
     }
 });

我的简单TestJSON是[OperationContract]

public string TestJSON(string id)
{
    Bikes b = new Bikes();
    b.Description = "blah blah";
    b.Name = "DMX100";
    b.Make = "2010";
    b.ID = id;
    string bikeJson = JsonConvert.SerializeObject(b);
    return bikeJson;
}

我知道使用Breakpoint调用此方法,但参数“id”为null。 我在这里缺少什么?

2 个答案:

答案 0 :(得分:2)

您的服务需要一个名为id的参数,而在客户端,您使用BikeId作为参数名称发送该值。

要么TestJSON方法签名中的参数名称为:

public string TestJSON(string BikeId) {/*...*/}

或修改客户端的data对象:

$.ajax({
  type: "POST",
  url: "MyService.svc/TestJSON",
  data: '{"id":"'+ id + '"}', // <------
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    alert(msg);
  },
  error: GetFailedMessage
});

答案 1 :(得分:1)

我猜一点,但是当浏览器将它作为'BikeId'传递时,服务可能会将数据元素的名称推断为'id'?

相关问题