Sending an empty array in webapi

I want to send POST an empty javascript [] array to webAPI and create an empty list of integers. I also want this to be if I send javascript null to the webAPI so that it assigns null to a list of integers.

JS:

 var intArray = []; $.ajax({ type: 'POST', url: '/api/ListOfInts', data: {'' : intArray}, dataType: 'json' }); 

C # webapi

 [HttpPost] public void ListOfInts([FromBody]List<int> input) 

Problem 1) JQuery refuses to send data {'' : []} as an email payload. As soon as I add something to the array, it works, for example, {'' : [1,2,3]}

Problem 2) Passing an empty js array to the controller yields zero Based on what I read, even if I get it to publish an empty array, it initializes the list as null. In the solutions discussed, it is such that the list is always initialized as empty, but I do not want this. I want it to be empty in some cases (when null / undefined is sent to it), and when [] sent, it should be initialized as empty.

Edit: see https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1 on why I use {'' : []}

+7
javascript jquery c # asp.net-web-api
source share
3 answers

Use JSON.stringify(intArray) and contentType: 'application/json' for me:

 $.ajax({ url: "/api/values", method: "POST", contentType: 'application/json', data: JSON.stringify([]) }); 

enter image description here

 $.ajax({ url: "/api/values", method: "POST", contentType: 'application/json', data: null }); 

enter image description here

 $.ajax({ url: "/api/values", method: "POST", contentType: 'application/json', data: JSON.stringify([1, 2, 3]) }); 

enter image description here

+21
source share
 data: {'' : intArray}, 

an empty key name is not allowed in JSON.

Just send an array.

 data: intArray, 
+1
source share

1. Use JSON.stringify () to convert the javascript object to a JSON string.

2. Use contentType: 'application / json' as this is the correct MIME media type for JSON. What is the correct JSON content type?

3 dataType not required

data : JSON.stringify (intArray), contentType : 'application / json'

+1
source share

All Articles