Bilal Hussain Bilal Hussain - 1 year ago 101
Ajax Question

Passing HttpPostedFileBase and other variables in ajax POST to mvc controller

I have been trying to post a file and some variables to my controller action using ajax, but I am getting null parameters for both of my variables.
Below is my ajax call

$("#btn-upload").on("click", function () {
var rows =$("[name='rows']").val();
var formData = new FormData($('#excel-upload-form')[0]);
var Data = formData+"&rows="+rows;
$.ajax({
url: '/MVC/UploadExcel/UploadExcel',
type: 'POST',
data: Data,
cache: false,
contentType: false,
processData: false,
success: function (result) {
if (result=='True') {
$(".alert-success").show();
}
else {
$(".alert-danger").show();
}
},
error: function (jqXHR, textStatus, errorThrown) {
$(".alert-danger").show();
},

});
});


and my controller action is

[HttpPost]
public bool UploadExcel(HttpPostedFileBase uploadedFile, int? rows)
{
var excelUtility = new ExcelUtilityService();
bool success=false;
if ((uploadedFile != null || uploadedFile.ContentLength > 0)&& rows !=null)
{
success = excelUtility.ProcessFile(uploadedFile, rows);
}
return success;
}


If I pass only the file parameter in my ajax call it works fine but when I try to do it with multiple parameters e.g 'rows' in my code, both of the parameters become null in my controller action while post.

Answer Source

In order to add values to a FormData object, you need to use .append().

Modify your script to

$("#btn-upload").on("click", function () 
   var rows =$("[name='rows']").val();
   var formData = new FormData($('#excel-upload-form')[0]);
   formData.append('rows', rows); // modify
   $.ajax({
       url: '/MVC/UploadExcel/UploadExcel',
       type: 'POST',
       data: formData, // modify
       cache: false,
       contentType: false,
       processData: false,
       success: function (result) {
           ....
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download