7

I have a simple ajax call like:

$.ajax({
   url: ... ,
   data: { anArray: [] },
   ...
});

and the controller's action:

public ActionResult Test(int[] anArray) {
   ...
}

seems that anArray is null instead of empty array.

I tried also with

  • List<int>
  • string[]
  • object[]

but for all of above, I see null for anArray parameter.

I read similar questions but there are related to model parameters, I don't have, here, model.

How to receive an empty array in controller's action ? What should I do ?

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221

1 Answers1

3

It seems that MVC maps empty arrays to a null; this is by design for some reason. I guess you can't do much with an array of zero items anyway.

It seems that your best bet is to instantiate the array yourself if it does come through as null:

        public ActionResult Test(int[] anArray)
        {
            anArray = anArray ?? new int[0];

            //...
        }
Darren Gourley
  • 1,798
  • 11
  • 11