我需要将对象从 javascript 传递到 MVC 控制器。我这样做是这样的:
$.ajax({
type: 'POST',
url: '/Companies/Edit/',
dataType: 'json',
data: {
Id: id,
Name: name,
Adress: adress,
NIP: nip,
File: file
},
success: function (data) {
//...
},
error: function (xhr, ajaxOptions, error) {
alert('Błąd: ' + xhr.responseText);
}
});
我的 ViewModel 看起来像这样:
public class CompanyEditViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string NIP { get; set; }
public System.Web.HttpPostedFileBase File { get; set; }
}
和这样的控制器:
public ActionResult Edit(CompanyEditViewModel company) { ... }
问题是File
控制器中的字段始终为空,但 Firebug 显示该文件存在。所以我的问题是:如何通过包含文件的字段传递 javascript 对象?
编辑
根据这里的回答:我尝试使用FormData
发送我的对象:
var formdata = new FormData(viewModel);
$.ajax({
url: '/Companies/Edit/',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
但文件仍然为空。所以我为单独的文件编辑了控制器:
public ActionResult Edit(CompanyEditViewModel company, HttpPostedFileBase dropImage) {...}
...从javascript对象中删除字段文件viewModel
并再次尝试使用FormData
:
var formdata = new FormData(viewModel);
formdata.append('dropImage',file);
$.ajax({
url: '/Companies/Edit/',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
dropImage
在控制器中仍然为空。