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?
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
datainajaxmethod 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:
No js here, server code is the same.