Sending array of objects to WCF

后端 未结 3 1051
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 15:39

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

相关标签:
3条回答
  • 2021-01-23 16:02

    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.
    
    0 讨论(0)
  • 2021-01-23 16:17

    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

    0 讨论(0)
  • 2021-01-23 16:17

    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.

    0 讨论(0)
提交回复
热议问题