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?

asked Sep 15, 2018 at 18:37
1

1 Answer 1

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)
{
 ...
}
answered Sep 15, 2018 at 18:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.