1

My Web API cannot recognize array parameters. I have an array in front-end like this [1, 2, 3, 4, 5]. Now I want to pass it from the JSON body(not URL) to a Web API as follow:

Back-end Code:

// POST /api/result
[HttpPost]
public IHttpActionResult GetResult([FromBody]int[] ids)
{
    //do something
}

Front-end code(jQuery):

var array = new Array("1", "2", "3", "4", "5");
var ids = Json.stringify(array);

$.ajax({
    type: "POST",
    url: "/api/result",
    data: ids,
    success: function (data, state) {
        alert("success!");
    },
    dataType: "json"
})

But what the api got is "[]" instead of ["1", "2", "3", "4", "5"].

How to solve this problem?

1
  • data: {ids:ids}, try passing with JSON format in your ajax Commented Apr 6, 2018 at 5:41

1 Answer 1

1

Just add one more property tu $.ajax function

$.ajax({
    type: "POST",
    contentType: 'application/json; charset=utf-8',
    /*rest configuration*/
}

Then server side will be able to understand how to parse stringified content.

Some theory behind this issue: https://blog.codenamed.nl/2015/05/12/why-your-frombody-parameter-is-always-null/

Sign up to request clarification or add additional context in comments.

1 Comment

This is what exactly I ignored! And the problem was perfectly solved! Thank you!

Your Answer

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.