kitty sarvaj kitty sarvaj - 6 months ago 14
Ajax Question

Ajax Post Multiple Objects to WebApi 2

i am passing the JavaScript array objects through ajax post to my web API 2 below is my code, i am getting null value in my 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 I am getting Null value in my Contact list //

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

Answer

Because you are not posting an array of contacts. You are posting an object with property names of the different contacts. Try changing your js to:

$(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"
    });
});