FormData append item in array

后端 未结 2 1322
隐瞒了意图╮
隐瞒了意图╮ 2020-12-07 00:55
 public List Regions { get; set; }

in model called News.An Region Model is

public class Region
    {
        public i         


        
相关标签:
2条回答
  • 2020-12-07 01:47
     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,
                ....
            });
    
    0 讨论(0)
  • 2020-12-07 01:53

    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])
    }
    
    0 讨论(0)
提交回复
热议问题