Array Parameter Empty for jQuery Ajax Call to MVC

1261 views javascript
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?

answered question

1 Answer

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)
{
    ...
}

posted this

Have an answer?

JD

Please login first before posting an answer.