在我的应用程序中,我想使用jQuery和Ajax保存数据。我有一个WCF服务。 我想使用ajax保存一个对象列表。我已尝试使用以下代码,但它 没有用。
jquery代码:
var listOfObjects=new Array();
//creating list of objects
for(var i=0;i<5;i++)
{ var MyEntity=new Object();
MyEntity.TestId =i;
MyEntity.TestId =i+"testName";
listOfObjects.push(MyEntity);
}
//Saving info
$.ajax({
type: "POST",
async: false,
data: JSON.stringify(listOfObjects),
url: "../ServiceLayer/myService.svc/SaveResults",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("success");
},
error: function () {
alert("Error");
}
});
WCF:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void SaveLabResults(List<MyEntity> myEntity)
{
var lstEntities=myEntity;
}
实体:
[DataContract]
public class MyEntity
{
[DataMember]
public string TestId { get; set; }
[DataMember]
public string TestName { get; set; }
}
通过这种方式我正在尝试发送列表数据。但内部服务器错误即将到来。我没有得到实际上我错的地方。还有其他方法将对象列表发送到WCF吗?
由于
答案 0 :(得分:2)
jquery代码:
var listOfObjects=new Array();
//creating list of objects
for(var i=0;i<5;i++)
{ var MyEntity=new Object();
MyEntity.TestId =i;
MyEntity.TestId =i+"testName";
listOfObjects.push(MyEntity);
}
var jsonList=JSON.stringify(listOfObjects);
var dataToSend = '{"myEntity":'+jsonList+'';
//Saving info
$.ajax({
type: "POST",
async: false,
data: dataToSend,
url: "../ServiceLayer/myService.svc/SaveResults",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("success");
},
error: function () {
alert("Error");
}
});
WCF:
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void SaveLabResults(List<MyEntity> myEntity)
{
var lstEntities=myEntity;
}
<强>实体:强>
[DataContract]
public class MyEntity
{
[DataMember]
public string TestId { get; set; }
[DataMember]
public string TestName { get; set; }
}
我缺少的是
1.var jsonList=JSON.stringify(listOfObjects);
2.var dataToSend = '{"myEntity":'+jsonData+'';
第二点myEntity键应该在最终的json对象中。并且键应该 与wcf方法对象参数相同。
由于
答案 1 :(得分:1)
在您的客户端代码中调用BodyStyle = WebMessageBodyStyle.Bare
之前,请尝试使用JSON.stringify
作为服务器方法,或在JSON数据中引入名为“myEntity”的根元素。
答案 2 :(得分:0)
可能是这一个是错误:
//creating list of objects
for(var i=0;i<5;i++)
{ var MyEntity=new Object();
MyEntity.TestId =i;
MyEntity.TestId =i+"testName";
listOfObjects.push(MyEntity);
} //-------------------^--------------shouldn't it be capital M
并在ajax函数中:
$.ajax({
type: "POST",
async: false,
data: {data : JSON.stringify(listOfObjects)}, //<---not quite sure about it.