Wawa Wawa - 4 months ago 17
C# Question

Asp.net MVC - How to upload files without pressing send button? Automatically uploaded once selected the files


How can i make the upload file action automatically once the files selected. means that the action will go to index action without pressing any button? Thanks in advance..


enter image description here


View


<form action="@Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
@Html.AntiForgeryToken()
<table >
<tr>
<td>
<label>Name:</label>
<input type="text" name="faxnumber" />
</td>
</tr>
<tr>
<td>
<label>Select File:</label>
<input type="file" name="files" id="file" multiple="multiple" />
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Send" id="btnSubmit" />
</td>
</tr>
@ViewBag.Message
</table>
</form>



javascript


<script>
document.getElementById("file").onchange = function () {
document.getElementById("form").submit();
}
</script>



Controller


public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
//some code here
}

Answer

Your code will work fine if you change your submit button name value to anything other than "submit".

 <input type="submit" name="notsubmit" value="Send" id="btnSubmit" />

This is an interesting behavior ! I really do not know why it does not submit when the name attribute value is "submit". I will update the answer when i get any more info.