简体   繁体   中英

How to pass a list of integer from js to c# controller

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第一种方法 Second method request object: 第二种方法

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});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM