使用 FormData MVC 将文件和列表发布到 MVC 控制器
Posting File and List to MVC controller Using FormData MVC
我正在尝试 post 使用 FormData 将一个文件和一个列表发送到 MVC 控制器,但是在点击控制器时该列表似乎是空的。
表单数据:
var formData = new FormData();
formData.append("AttachedFile", files[0]);
formData.append("Items", invoice.serialize());
formData.append("CustomerId", 1);
formData.append("RevenueHeadId", demandNoteObject.RevenueHeadId);
型号:
public int CustomerId { get; set; }
public int RevenueHeadId { get; set; }
[DataType(DataType.Upload)]
public HttpPostedFileBase AttachedFile { get; set; }
public List<Items> Items { get; set; }
控制器:
[HttpPost]
public ActionResult Create(InvoiceCreateModel model)
JQuery:
$.ajax({
type: "POST",
url: "@Url.Action("Create", "")",
datatype: "Json",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$.ajax({
type: 'POST',
url: '@Url.Action("Create", "yourControllerName")',
data: formData,
contentType: false,
processData: false,
success: function (data) { ...}
});
试试这个
编辑
因为 Items 是对象的集合,所以您必须为每个对象添加一个索引
var index = 0;
for(var item of invoice){
var pair = item[key];
formData.append("Items[" + index + "].yourField", pair.yourField);
index++;
}
我正在尝试 post 使用 FormData 将一个文件和一个列表发送到 MVC 控制器,但是在点击控制器时该列表似乎是空的。
表单数据:
var formData = new FormData();
formData.append("AttachedFile", files[0]);
formData.append("Items", invoice.serialize());
formData.append("CustomerId", 1);
formData.append("RevenueHeadId", demandNoteObject.RevenueHeadId);
型号:
public int CustomerId { get; set; }
public int RevenueHeadId { get; set; }
[DataType(DataType.Upload)]
public HttpPostedFileBase AttachedFile { get; set; }
public List<Items> Items { get; set; }
控制器:
[HttpPost]
public ActionResult Create(InvoiceCreateModel model)
JQuery:
$.ajax({
type: "POST",
url: "@Url.Action("Create", "")",
datatype: "Json",
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
$.ajax({
type: 'POST',
url: '@Url.Action("Create", "yourControllerName")',
data: formData,
contentType: false,
processData: false,
success: function (data) { ...}
});
试试这个
编辑 因为 Items 是对象的集合,所以您必须为每个对象添加一个索引
var index = 0;
for(var item of invoice){
var pair = item[key];
formData.append("Items[" + index + "].yourField", pair.yourField);
index++;
}