【问题标题】:Ajax Post Multiple Objects to WebApi 2Ajax 将多个对象发布到 WebApi 2
【发布时间】:2016-05-19 10:20:00
【问题描述】:

我通过 ajax post 将 JavaScript 数组对象传递给我的 Web API 2 下面是我的代码,我在我的 Web API 中得到空值

 <script>
    $(document).ready(function () {
    var Contacts = { steve: {},bill: {}, RON: {}, dan: {}, };
    Contacts.bill = {  Name: "Bill", UserName: "Gates",  MobileNUmber: "(206) 555-5555",};
    Contacts.steve = { Name: "Steve", UserName: "Jobs",   MobileNUmber: "(408) 555-1111",};
    Contacts.jon = {  Name: "Steve",  UserName: "Jobs",  MobileNUmber: "(408) 555-2222", };
    Contacts.RON = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 333-5555", };
    Contacts.dan = {  Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 444-5555",};
    Contacts.qwe = { Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 555-5555",};
    var ContactList =  JSON.stringify(Contacts)
    console.log(ContactList);
    var baseUrl = "http://localhost:55942/";

          $.ajax({
        type: "POST",
        data: ContactList,
        url: baseUrl + 'api/CONTACT/comparecontacts',
    contentType: "application/json"
});
});
</script> 

// WEB API 我的联系人列表中的值为 Null //

    public class CONTACTController : ApiController
   {
    [HttpPost]
    public  IHttpActionResult comparecontacts(List<ContactList> ContactList)
    {
        return Ok();
    }
}

【问题讨论】:

    标签: javascript ajax cordova c#-4.0 asp.net-web-api


    【解决方案1】:

    因为您没有发布联系人数组。您正在发布具有不同联系人的属性名称的对象。尝试将您的 js 更改为:

    $(document).ready(function () {
        var contacts = [];
        contacts.push({ Name: "Bill", UserName: "Gates", MobileNUmber: "(206) 555-5555", });
        contacts.push({ Name: "Steve", UserName: "Jobs", MobileNUmber: "(408) 555-1111", });
    
        //..
    
        var baseUrl = "http://localhost:55942/";
        $.ajax({
            type: "POST",
            data: JSON.stringify(contacts),
            url: baseUrl + 'api/CONTACT/comparecontacts',
            contentType: "application/json"
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2017-05-03
      • 2019-03-30
      • 2015-03-08
      • 2015-04-15
      • 2020-11-25
      • 2013-07-03
      • 2012-11-14
      • 2012-03-20
      • 2015-05-03
      相关资源
      最近更新 更多