Nathan Liu
Nathan Liu

Reputation: 2205

Posting an object and a file in the same call to the server with jQuery.ajax

I'm trying to make a client side post to the following MVC action method:

[HttpPost]
public void Create(ProductModel product, HttpPostedFileBase imageFile)
{
    productServices.AddProduct(product, imageFile);
}

This is straightforward with a type="submit" button, however in my particular case I need to do it with an ajax call.

I can just pass the ProductModel as JSON easy enough.

$.ajax({
    url: '/Product/Create',
    type: 'POST',
    data: JSON.stringify({product: {
            Id: 1,
            Name: "SomeName"
        }
    }),
    contentType: 'application/json; charset=utf-8',
    success: function (data) {
        alert("Product Created!");
    }
});

I can also pass the file as FormData

var imageFileData = new FormData();
imageFileData.append('imageFile', myFileObject);

$.ajax({
    url: '/Product/Create',
    data: imageFileData,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data);
    }
});

However I can't seem to combine the 2 as separate parameters in the same call as they are fundamentally different contentTypes.

Is this possible? Am I going about this the wrong way? Any help would be appreciated.

Upvotes: 1

Views: 898

Answers (1)

Musa
Musa

Reputation: 97672

You can add the json to the FormData just like you add the file

var imageFileData = new FormData();
imageFileData.append('imageFile', myFileObject);
imageFileData.append('product', JSON.stringify({product: {
            Id: 1,
            Name: "SomeName"
        });

$.ajax({
    url: '/Product/Create',
    data: imageFileData,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data);
    }
});

of you can add the form itself to FormData

$.ajax({
    url: '/Product/Create',
    data: new FormData(theFormElement),
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function (data) {
        alert(data);
    }
});

Upvotes: 2

Related Questions