I need to pass object from javascript to MVC controller. I do this in this way:
$.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);
}
});
My ViewModel looks like this:
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; }
}
And controller like this:
public ActionResult Edit(CompanyEditViewModel company) { ... }
The problem is field File
in controller is always null, but Firebug shows that file exists. So my question is: how can I pass javascript object with field contains file?
Edit
In according to answer from here: I tried use FormData
for sending my object:
var formdata = new FormData(viewModel);
$.ajax({
url: '/Companies/Edit/',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
but file is still null. So I edited controller for separate file:
public ActionResult Edit(CompanyEditViewModel company, HttpPostedFileBase dropImage) {...}
... deleted field File from javascript viewModel
object and tried again use FormData
:
var formdata = new FormData(viewModel);
formdata.append('dropImage',file);
$.ajax({
url: '/Companies/Edit/',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
});
dropImage
in controller is still null.