Reputation: 13
I am able to send a single complex type from ajax to controller however not able to pass a list, always comes up null. *** Code has been updated to show successful passing.
public class EntityAliasTest
{
public int IDTEMP1 { get; set; }
public string NAMETEMP1 { get; set; }
}
[HttpPost]
public IActionResult SaveEntityAliases([FromBody]
List<EntityAliasTest> postData)
{
var es = ModelState.SerializeErrors();
return Json(new[] { postData, es });
}
var aliasList = new Array();
var o = { IDTEMP1 : 0, NAMETEMP1: 'test 0' };
aliasList.push(o);
o = { IDTEMP1 : 1, NAMETEMP1: 'test 1' };
aliasList.push(o);
o = { IDTEMP1 : 2, NAMETEMP1: 'test 2' };
aliasList.push(o);
var postData= JSON.stringify(aliasList);
$.ajax({
url: "DataAdministration/EntityAlias/SaveEntityAliases",
type: "POST",
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: postData,
}).done(function (data) {
Upvotes: 1
Views: 2868
Reputation: 24
Based on your ajax call, you are sending a single object that contains a list. So your controller will also expect an object with that kind of structure.
Instead of this: var data = { postData: aliasList }; var data2send = JSON.stringify(data);
You can try: var data2send = JSON.stringify(aliasList);
You can use online json validator to check if you pass a valid json data. You can refer on the link below.
Hope it will help.
Upvotes: 1