1

I have a simple MVC api method:

[System.Web.Http.HttpPost]  // Important: it is not System.Web.Mvc.HttpPost
public void MyMethod(object[] arr)
{
    ...
}

I am calling it using this javascript:

$.ajax({
    url: url,
    method: "POST",
    data: { arr: ['1','2']},
    dataType: "json",
    traditional: true,
    error: function (e) {
        ...
    },
    success: function (res) {
        ...
    }
});

The call is successful but the value of arr in the C# code is an empty array (string[0]). I found multiple samples of such calls suggesting mainly adding the traditional: true but it still doesn't work. I tried also providing data in different formats, e.g.:

  • data: { arr: ['1','2']}
  • data: { ['1','2']}
  • data: ['1','2']
  • JSON.stringify(['1', '2'])

and none of these work. Ideas?

Vladimir
  • 1,425
  • 16
  • 31
  • Possible duplicate of [Pass array to mvc Action via AJAX](https://stackoverflow.com/questions/5489461/pass-array-to-mvc-action-via-ajax) – Dmitry Pavlov Sep 15 '18 at 18:59

1 Answers1

1

You need to specify the [FromBody] parameter:

[System.Web.Http.HttpPost]  // Important: it is not System.Web.Mvc.HttpPost
public void MyMethod([FromBody] object[] arr)
{
    ...
}

And your code should be:

$.ajax({
    url: url,
    method: "POST",
    data: ['1','2'],
    dataType: "json",
    traditional: true,
    error: function (e) {
        ...
    },
    success: function (res) {
        ...
    }
});

If you specify a key/value like {Arr: ['1', '2']} then you should create a structure for your body:

class MyMethodPostJson
{
    public List<string> Arr;
}

And use:

[System.Web.Http.HttpPost]  // Important: it is not System.Web.Mvc.HttpPost
public void MyMethod([FromBody] MyMethodPostJson arr)
{
    ...
}
Blue
  • 22,608
  • 7
  • 62
  • 92