2

I am trying to migrate to an ASP.NET 6 API controller and my POST data from my JS function is showing as null.

I have the following json request:

// searchTerms is an array with 2 properties, Value and Type
$.ajax({
    type: 'Post',
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({
        searchTerms
    })

if I POST this to an ASP.NET 6 MVC controller:

public ActionResult Search(List<SearchTerm> searchTerms)

Then my searchTerms list is properly populated.

If I POST to an API Controller

[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/search")]
public IHttpActionResult Search([FromBody] List<SearchTerm> searchTerms)

Then searchTerms is null.

I have tried to change the contentType, dataType, remove the stringify function to no avail.

I have tried to changed the signature to

public IHttpActionResult Search([FromBody] dynamic value)

And see the following, so obviously I'm not binding properly?

enter image description here

Here is my SearchTerm model:

public class SearchTerm
{
    public string Value { get; set; }
    public string Type { get; set; }
}
2
  • Could you post your SearchTerm model? Commented Nov 7, 2017 at 7:54
  • 1
    I think you're passing a model which has a list of SearchTerms in it instead of passing a list directly. But that's just a guess. Commented Nov 7, 2017 at 8:05

1 Answer 1

4

Instead of:

data: JSON.stringify({
    searchTerms
})

Change your $.ajax call to use just:

data: JSON.stringify(searchTerms)

You are sending JSON that looks something like:

{
    "seachTerms": [
        ...
    ]
}

With the change I suggested, this would just be a simple JSON array, which should work in your example.

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

2 Comments

Quick question, how do I now add other paramaters? (ie, an integer)
Have a look at @Nkosi's answer here: stackoverflow.com/a/44599682/2630078 and be sure to upvote his answer if it helps.

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.