Home > Software engineering >  How to pass a list of integer from js to c# controller
How to pass a list of integer from js to c# controller

Time:08-22

I have code send a list of integers to the controller I use JQuery post and I want to replace it with fetch however my code not working correctly and I have no idea how to solve it my old code:

 $.post(url, { ids: id });

code using fetch

  var ids = new FormData();
  ids.append('ids',id);
  fetch(url, { method: 'POST', body: ids });

controller

[HttpPost]
public async Task<IActionResult> Create(int[] ids)
{
  return Json(ids)
}

First method mapping correctly and the request object as shown in the image below First method Second method request object: Second method

CodePudding user response:

To fill the FormData with an array, you need to do the following

var url='url'; //replace With correct url

var ids=[1,2,3,4];
//ids.push(5);

var formData = new FormData();

for (var i = 0; i < ids.length; i  ) {
 formData.append('ids[]', ids[i]);
}

fetch(url, { method: 'POST', body: formData});
  • Related