Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending empty array to webapi

I want to POST an empty javascript array [] to webAPI and have it create an empty list of integers. I also want it so if I post javascript null to webAPI that it assigns null to the 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 the post payload. As soon as I add something in the array it works such as {'' : [1,2,3]}

Problem 2) Passing empty js array to controller gives null Based on what i read even if I do get it to post an empty array, it will initialize the list as null. Discussed solutions have it so that the list is always initializes as empty but I don't want that. I want it to be null in some case (when null/undefined is sent to it) and when [] is sent it should initialize as empty.

Edit: See https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1 about why I am using {'' : []}

like image 396
LearningJrDev Avatar asked Jun 07 '16 20:06

LearningJrDev


People also ask

How do you send an empty array?

Basic example of empty array:$emptyArray = ( array ) null; var_dump( $emptyArray );

Should API return null or empty array?

If a field has no value, it shall be null. But string fields without value should also be represented as null , not "" . Note: Empty arrays shall not be null . If a field is some kind of list and it is represented by an array, an array shall be returned, even if empty.

How do you push an element to an empty array?

How do you push values in an empty array? Answer: Use the array_push() Function You can simply use the array_push() function to add new elements or values to an empty PHP array.

Can an array element be empty?

The length property sets or returns the number of elements in an array. By knowing the number of elements in the array, you can tell if it is empty or not. An empty array will have 0 elements inside of it.


1 Answers

Use JSON.stringify(intArray) and contentType: 'application/json' works 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

like image 172
tmg Avatar answered Oct 03 '22 22:10

tmg