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
May be this one is the error:
//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
and in the ajax function:
$.ajax({
type: "POST",
async: false,
data: {data : JSON.stringify(listOfObjects)}, //<---not quite sure about it.
jquery code :
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;
}
Entity:
[DataContract]
public class MyEntity
{
[DataMember]
public string TestId { get; set; }
[DataMember]
public string TestName { get; set; }
}
What i am missing was
1.var jsonList=JSON.stringify(listOfObjects);
2.var dataToSend = '{"myEntity":'+jsonData+'';
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.
Thanks
Try BodyStyle = WebMessageBodyStyle.Bare
for your server method or introduce a root element named "myEntity" in your JSON data prior to calling JSON.stringify
in your client code.