Reputation: 2945
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?
Here is my SearchTerm model:
public class SearchTerm
{
public string Value { get; set; }
public string Type { get; set; }
}
Upvotes: 2
Views: 915
Reputation: 93283
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.
Upvotes: 4