HttpPostedFileBase is null when using AJAX in ASP MVC 5

10,491

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)
{
   ...
}
Share:
10,491
Code Pope
Author by

Code Pope

Software developer for more than a decade. "From my point of view, code is the light that illuminates the darkness, even if it does not dissolve it, and a spark of divine light is within each of us."

Updated on June 26, 2022

Comments

  • Code Pope
    Code Pope almost 2 years

    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?