Naresh Ravlani
Naresh Ravlani

Reputation: 1620

MVC Core : Upload file through Ajax request and return JSON object without redirect

I have a requirement where I want to upload an excel file to the controller, read the file, process its data and send it back to the same view as the JSON object.

I want to achieve this using AJAX call as I want to capture its success callback and manipulate DOM as per received response. I have tried a few things but I am not able to hit the controller. Any help on this is appreciated.

Below shown is my JS, HTML and C# code :

function SubmitInfo() {
    var formData = new FormData();
    formData.append('file', $('#fileInput')[0].files[0]); // myFile is the input type="file" control

    var _url = '@Url.Action("Upload", "CrossValidation")';

    $.ajax({
        url: _url,
        type: 'POST',
        data: formData,
        processData: true,  // tell jQuery not to process the data
        contentType: false,  // tell jQuery not to set contentType
        success: function (result) {
            //manipulate DOM and bind response with Kendo grid
            alert("result");
        },
        error: function (jqXHR) {
        },
        complete: function (jqXHR, status) {
        }
    });
}
<div class="col-md-4">
    <input id="fileInput" type="file">
</div>
<div class="col-md-4">
    <input type="submit" value="Upload file" onclick="SubmitInfo()"/>
</div>
public JsonResult Upload(IFormFile formData)
{
    //Do something here....
    return Json("");
}

Upvotes: 1

Views: 643

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93003

There are two obvious problems in the code you've posted:

  1. processData: true. By setting this to true (the default), you're asking jQuery to attempt to turn the data you're providing into a query string, which is not what you want. Instead, you want to set this to false, which will ask jQuery to leave the data alone and pass it on to the underlying XMLHttpRequest as is, where the data will be formatted correctly as multipart/form-data.
  2. The name argument passed to formData.append must match the name of your IFormFile parameter in the ASP.NET Core MVC Controller. You're using file in the the former and formData in the latter, so you'll need to change one of them so that they're the same.

Upvotes: 2

Related Questions