将对象数组发送到WCF [英] Sending array of objects to WCF
问题描述
在我的应用程序中,我想使用jQuery和Ajax保存数据.我有一个WCF服务. 我想使用ajax保存对象列表.我尝试了以下代码,但它 无法正常工作.
In my application i want to save the data by using jQuery and Ajax.I have a WCF Service. I want to save a List of Objects by using ajax.I have tried with following code, but it is not working.
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吗?
In this way i am trying to send the list data.But internal server error is coming.I am not getting where actually i am wrong.Is there any other way to send the list of objects to WCF ?
谢谢
推荐答案
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方法对象参数相同.
The 2nd point myEntity key should be there in the final json object.And the key should be same as the wcf method object parameter.
谢谢
这篇关于将对象数组发送到WCF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!