jqueryajaxasp.net-mvcasp.net-mvc-ajaxjquery-ajax

JQuery ajax - how to pass an array parameter with null value


I need to pass an array parameter to my ASP.NET backend. It looks like this:

$.ajax({ url: 'test', type: 'POST', data: { test: [1, 2] }})

And the generated form data is: test[]=1&test[]=2.

So far so good. But the problem occurs when I try to pass a null value inside an array:

$.ajax({ url: 'test', type: 'POST', data: { test: [1, null] }})

In this case for some reason generated form data looks like: test[]=1&test[1]=.

Please notice that second test segment has a numeric index. This cannot be parsed correctly on the backend: segment with an index is ignored, so I don't have my null value on the backend.

Any idea how to make it working?


Solution

  • I solved it by using empty string instead of null:

    $.ajax({ url: 'test', type: 'POST', data: { test: [1, ''] }})

    In this case form data looks like this: test[]=1&test[]= and is correctly parsed on the backend to 1 and null.