In my project, there is an upload.ascx
file that will be loaded inside a Jquery Popup.
The upload.ascx
file contains a File Upload
control that uploads .xlsx and .xls
files. To validate the file uploads and prevent unnecessary files from being uploaded, I have added a JavaScript
function.
Whenever there is a change in the FileUpload control or when the Submit button is clicked, the validation function is called.
The File Upload Validation Function works correctly for both scenarios. However, my issue arises when the validation function returns false. After displaying an alert message, the page redirects to a specific URL (
localhost/Admin/Authorization/AcceptFile.aspx
) even though the function should prevent this from happening.
Upon further investigation, I noticed that if the wrong file is uploaded, the redirection occurs without calling the Action Result, which should be prevented.
<% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
JavaScript Function:
function checkfile(sender) {
var validExts = new Array(".xlsx", ".xls");
var fileExt = sender.value;
var strValue = false;
fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
if (validExts.indexOf(fileExt) < 0) {
ShowMessage(-1, "Invalid file selected, valid files are .xlsx and .xls types.");
strValue = false;
}
else {
strValue = true;
}
return strValue;
}
upload.ascx Code:
<div>
<% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<input type="file" id="fileAuthorization" name="fileAuthorization" onchange="checkfile(this);" />
<input type="submit" id="btnSave" name="btnSave" value="Upload" onclick="javascript:return checkfile(document.getElementById('fileAuthorization'))" />
<%} %>
</div>