Code Pope
Code Pope

Reputation: 5449

HttpPostedFileBase is null when using AJAX in ASP MVC 5

I am using JQuery.AJAX to upload files to the server in ASP.NET MVC 5. The code of my view is:

<input type="file" size="45" name="file" id="file">

The Javascript is:

<script>
$('#file').on("change", function () {
    var formdata = new FormData($('form').get(0));
    CallService(formdata);
});
function CallService(file) {
    $.ajax({
        url: '@Url.Action("Index", "Home")',
        type: 'POST',
        data: file,
        cache: false,
        success: function (color) {
            ;
        },
        error: function () {
            alert('Error occured');
        }
    }); 
}

And finally the code of the HomeController.cs:

        public ActionResult Index (HttpPostedFileBase file)
    {
       ...

    }

But everytime the Index action is called, the HttpPostedFileBase Object is empty. I have read all threads about this issue in SO, but could not find an answer. I have entered the right name and it fits with the parameter name in the controller. What is wrong with the code, so that the object is always empty?

Upvotes: 3

Views: 12100

Answers (1)

Code Pope
Code Pope

Reputation: 5449

So the right code for this problem: View:

<form>
    <input type="file" size="45" name="file" id="file">
</form>

The Javascript:

<script>
    $('#file').on("change", function () {
        var formdata = new FormData($('form').get(0));
        CallService(formdata);
    });

    function CallService(file) {
        $.ajax({
            url: '@Url.Action("Index", "Home")',
            type: 'POST',
            data: file,
            cache: false,
            processData: false,
            contentType: false,
            success: function (color) {
                ;
            },
            error: function () {
                alert('Error occured');
            }
        });
    }
</script>

And finally the code of the HomeController.cs:

public ActionResult Index (HttpPostedFileBase file)
{
   ...
}

Upvotes: 3

Related Questions