0

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.

Community
  • 1
  • 1
1_bug
  • 5,505
  • 4
  • 50
  • 58
  • 1
    You need to use `FormData` - refer [this answer](http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it-in-mvc/29293681#29293681) –  Jul 23 '15 at 09:22
  • @StephenMuecke: if I put my `viewModel` object to controller of `FormData` file is still null, if I send file apart by `.append` method is null too. I can't use html form for `FormData` constructor because I collect separately fields and send it to controller. – 1_bug Jul 23 '15 at 09:36
  • You can append both individual properties and and files - [refer the documentation here](https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects) for more detail (although its not clear why your cant just use the constructor to serialize the form controls include file inputs) –  Jul 23 '15 at 09:50

0 Answers0