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?
-
Possible duplicate of Pass array to mvc Action via AJAXDmitry Pavlov– Dmitry Pavlov2018年09月15日 18:59:55 +00:00Commented Sep 15, 2018 at 18:59
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)
{
...
}
Comments
Explore related questions
See similar questions with these tags.