Guilherme Longo
Guilherme Longo

Reputation: 2308

Handling input type file in asp net mvc

I have done a deep research trying to find the more pratical way to upload files from the client-side and I decided to go for the input type file html element.

Problem is: I get nothing in the controller and I am not able to see even the fakepath string been set in firebug.

View:

<form action="action" id="id" method="POST" enctype="multipart/form-data">
    <table id="tblId">            
        <tr>
            <td><input type="file" name="file" /></td>
        </tr>
    </table>
    <input type="submit" value="import" />
</form>   

As you can see, I am properly using enctype. Data is been sent to the controller as it should except that there is no data.

Controller:

[HttpPost]
public ActionResult opImportFile(FormCollection form) {


    var file = Request.Files["file"];
        if (file != null)
        {
            return Content("ok");
        }
        else
        {
            return Content("bad");
        }
}

And I am getting always "bad"! Too bad. Is there any other way I could try or am I doing somenthing wrong?

P.S -> It is a ajax request:

$('#formUpdStoringSettings').submit(function (e) {

    e.preventDefault();    
    var form = $(this);       
    alert($('input[name=file]').val()); //Here I am able to get the fakepath...
    alert(form.serialize());  //Here I get nothing...

    $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        data: form.serialize(),
        success: function (response) {
        }
   });
}

Upvotes: 0

Views: 5237

Answers (1)

Andy T
Andy T

Reputation: 9881

You probably will need to use a jQuery upload plug-in to be able to upload using AJAX.

Upvotes: 1

Related Questions