簡體   English   中英

如何將具有ajax文件的對象數組發送到asp.net MVC控制器?

[英]How to send an array of object having file with ajax to asp.net MVC controller?

數據上傳網格

我一直在嘗試使用 ajax 將每行中包含一個文件的多行(請參見上圖)發送到我的 MVC 控制器。 JavaScript 代碼-

var formData = new FormData();
$('#assFileTable tbody tr').each(function (index, item) {
    var tr = $(this);
    var description = tr.find('.dTableDescription').val();
    var docType = tr.find('.dTableDocType').val();
    var attachment = $('#row-' + index + '-Attachment').get(0).files[0];

    var assoFile = {
        Description: description,
        DocTypeId: docType,
        Attachment: attachment
    };
    formData.append('assoFiles', assoFile);
});

var request = new Request('/Setting/SaveAssociatedFiles/', {
        method: 'POST',
        body: formData
});
fetch(request).then(response => console.log(response.json()));

控制器方法-

public ActionResult SaveAssociatedFiles(List<TaskAssociatedFileViewModel> assoFiles)
{            
}

模型-

public class TaskAssociatedFileViewModel
{
    public string Description { get; set; }
    public int DocTypeId { get; set; }
    public string FilePath { get; set; }
    public HttpPostedFileBase Attachment { get; set; }
}

控制器方法被調用但獲取空值而不是發送數據。 我錯過了什么還是我必須做不同的事情?

據我了解,您只是在assoFiles鍵中發送表格的最后一行

var formData = new FormData();
let allDataArray = [];
    $('#assFileTable tbody tr').each(function (index, item) {
        var tr = $(this);
        var description = $(this).find('.dTableDescription').val();
        var docType = $(this).find('.dTableDocType').val();
        var attachment = $('#row-' + index + '-Attachment').get(0).files[0];

        var assoFile = {
            Description: description,
            DocTypeId: docType,
            Attachment: attachment
        };
        allDataArray.push(assoFile)

    });
    formData.append('assoFiles', allDataArray);
    var request = new Request('/Setting/SaveAssociatedFiles/', {
            method: 'POST',
            body: formData
    });
    fetch(request).then(response => console.log(response.json()));
  1. 創建一個空數組

    讓所有數據 = []

  2. 在 formData 空白數組中附加assoFile

    allData.push(assoFile)

  3. formData.append('assoFiles', allData);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM