FormData append item in array

ぃ、小莉子 提交于 2019-11-28 00:57:28

If your using FormData to send the data, you need to .append() each individual name/value to FormData. Since its a collection, you must include the collection indexer (which must be zero based and consecutive), for example

formData.append("Regions[0].Id", someValue);
formData.append("Regions[0].Name", someValue);
formData.append("Regions[1].Id", someValue);
formData.append("Regions[1].Name", someValue);

Since your doing this in a loop, you can use

for (var i = 0; i < region.length; i++) {
    formData.append("Regions[" + i + "].Id", region[i])
}
 var regionList = [];
    for (var i = 0; i < region.length; i++) {
        var item = {
            Id: region[i].Id,
            Name : region[i].Name,
        }
        regionList.push(item);
    }

    regionList = JSON.stringify({ "item": regionList });//Here "item" name should match the parameter name in your Action method name in controller (item in your case.)

Then pass the regionList object to $.ajax as data.

 $.ajax({
            type: 'POST',
            url: '@Url.Action("AddByRegion", "News")',
            data: regionList,

            contentType: false,
            processData: false,
            ....
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!