Posting Array using JSON & JQuery to a C# Web Api back end
Solution 1
Add in your headers. content-type :application/json
This should work.
Solution 2
What your JSON is sending is essentially this: an object with a property called list that then has a list of objects in it. You have one unnecessary redirection. Try to remove the list:
from the data you are sending and directly send the list as your parameter.
K.Sindhu
Updated on August 16, 2022Comments
-
K.Sindhu over 1 year
I have the following JQuery:
var dataToSend = { list: [{ Code: 'ABC', BusinessDate: '31-Jan-2012' }, { Code: 'DEF', BusinessDate: '31-Jan-2012' }] }; $.ajax({ type: 'POST', traditional: true, url: '/api/dashboard/post/', dataType: 'json', data: JSON.stringify( dataToSend), success: function (result) { alert('done'); }, error: function (result) { alert(result); } });
and the following method at on the server:
[System.Web.Http.HttpPost] public void Post(List<MyObject> list) { }
MyObjects definition:
public class MyObject { /// <summary> /// /// </summary> public string Code { get; set; } /// <summary> /// /// </summary> public string BusinessDate { get; set; } }
The method gets hit, but shows no results in the collection. If I change the parameter to be:
[System.Web.Http.HttpPost] public void Post(MyObject list) { // return new JsonResult(); }
and only pass through the first item in the collection, I receive the object with the data in the web api method without issue, it's only when trying to pass arrays that I seem to have a problem.
Fidler shows this as the JSON:
{"list":[{"Code":"ABC","BusinessDate":"31-Jan-2012"},{"Code":"DEF","BusinessDate":"31-Jan-2012"}]}
Could someone please explain what I am doing incorrectly which so I can not receive arrays?