[英]How to send Javascript File Object+ Data to MVC 6 Controller - ASP.NET 5
[英]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()));
創建一個空數組
讓所有數據 = []
在 formData 空白數組中附加assoFile
allData.push(assoFile)
formData.append('assoFiles', allData);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.