0

I am uploading a file in my ASP.NET MVC application. In the .ascx file, I have the following:

<form action="/Admin/Mail/ABC" enctype="multipart/form-data"  method="post">
<div>               
    <input type="file" name="file" id="file" />
    <input type="submit" value="Upload" id="UploadList" onclick="Origin.UploadOptOutList();"/>
</div>

in the .js file:

Origin.UploadList = function () {
    Origin.ajax({
        url: '/Admin/Mail/Upload',
        type: 'POST',
        dataType: 'json',
        success: function (data) {
            alert('success!');
        }
    });               
}

and the controller:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
    List<string> validIDs, invalidIDs;
    if (file.ContentLength > 0)
    {
        // do something
    }
}

When invoking the Action from .js, the 'file' is always NULL. Any idea what I am missing?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
GoldenUser
  • 365
  • 3
  • 6
  • 21

2 Answers2

2

At first, you cannot upload files asynchronously, unless you are using HTML5. If you still need this feature, you might want to try jQuery Form plugin.

At second, in your current js you are not sending any data with your request (field data in ajax method options), and that is why you are not receiving anything at server side. Moreover it is impossible to insert a file in this request as I have mentioned before. The most simple solution for you here is to give up with AJAX and let the file be uploaded in usual way:

View:

<form action="/Admin/Mail/Upload" enctype="multipart/form-data"  method="post">
    <div>               
        <input type="file" name="file" id="file" />
        <input type="submit" value="Upload" id="UploadList" />
    </div>
</form>

No js here, server code is the same.

Andrei
  • 55,890
  • 9
  • 87
  • 108
  • OK- the above would post the form to the action "/Admin/Mail/ABC". What if I want to display an error to the user in case the upload failed. I was hoping to do all that using jQuery. How can I achieve that now? – GoldenUser Apr 06 '12 at 19:12
  • You have two options: either keep everything synchronous, deal with whatever error occurs at server side and then return corresponding View (say the same View but with the error message), or you can have a look at the jQuery plugin mentioned in the post, and do prety much all you are trying to achieve, but using only jQuery. – Andrei Apr 06 '12 at 19:20
1

This is what you need

ScriptManager sm = ScriptManager.GetCurrent(Page);
            sm.RegisterPostBackControl(btnEditSubmit);
            Page.Form.Attributes.Add("enctype", "multipart/form-data");
            Page.Form.Attributes.Add("method", "post");