【问题标题】:POST AN OBJECT that has two properties (an array and a object) to a webapi? - asp.net webpi将具有两个属性(数组和对象)的对象发布到 webapi? - asp.net webpi
【发布时间】:2014-05-05 22:12:56
【问题描述】:

我有一个包含两个对象的 JSON 对象

第一个对象是一个名为 customer 的 json 对象

第二个是一个名为 dataserives 的 javascript 数组

我一直在尝试以以下格式将这两个对象发布到 webapia,

//this is the webapi method

public CustomerAndDataServices POST(CustomerAndDataServices cd)  
{
    return cd;    
}

我发布的 JSON 对象是这个

var customer ={name="clark"};

var dataservices=['email','internet', 'chat'];

var ds={''dataservices}

var data={

    customer:customer

    dataservices:ds

};

//this is how i post t  the webapi

$.ajax({

    url:'/api/myapi'

    data:{cd:dataservices}

});

//问题是我发这个的时候,绑定发生在客户对象上,但是dataservices数组是空的。

我已经看到如何通过将分配给数组的对象的属性设置为空字符串来将单个数组发送到 webapi

作为

$.ajax({

url:'/api/myapi'

data:{'':dataservices}

});

此解决方案工作正常,但它如何适用于我发布属性为对象和数组的 json 对象的场景?

谢谢

【问题讨论】:

    标签: javascript jquery asp.net-web-api


    【解决方案1】:

    试试这个:

     var customer = { name: "clark" };
     var dataservices = ['email', 'internet', 'chat'];
    
     //convert javascript object to JSON
     var cd = JSON.stringify({ customer: customer, dataservices: dataservices });
    
     $.ajax({
         url: '/api/myapi/',
         //declare ajax call is an HTTPPost
         method: 'POST',
         data: cd,
         //set data format as JSON
         contentType: 'application/json'
     });
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-08
      • 2013-10-14
      相关资源
      最近更新 更多