使用Javascript函数防止MVC表单提交

Prevent MVC form submit using Javascript Function

本文关键字:MVC 表单提交 Javascript 函数 使用      更新时间:2023-09-26

我有一个upload.ascx在我的项目。它将被加载到Jquery Popup中。

upload.ascx包含File Upload控制。文件上传控件将上传.xlsx and .xls文件。我已经添加了Java script函数来做这个验证(防止不必要的文件上传)。

Onchange of FileUpload控件和Onclick of Submit button将调用相同的Validation函数。

文件上传验证函数对两个调用都有效。如果用户单击提交按钮,则调用相同的函数并正常工作。

我的问题是:在我的验证函数我已经写了return false。在显示警报消息之后,页面被重定向到某个URL (localhost/Admin/Authorization/AcceptFile.aspx)。AcceptFile是我的ActionResult名称。这不应该发生。函数返回False。但是表单被重定向到上面的URL为什么?

我一直保持调试器在我的动作结果,没有得到调用,如果它的错误的文件(它的正确)。如果它是正确的文件,索引文件将加载成功消息(操作结果正在被调用并且工作正常).

我怀疑MVC表单。如果上传了错误的文件,重定向正在发生,而没有调用操作结果,则应停止此操作。

<% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data" }))
       {%>

我的Javascript函数:

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;
    }

我的上传。ascx代码:

<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>

我发现问题了

是我的怀疑是正确的。问题是

onsubmit = "javascript:return checkfile(document.getElementById('fileAuthorization'))"

this应该在Form标签中命名为Like this:

 <% using (Html.BeginForm("AcceptFile", "Authorization", FormMethod.Post, new { enctype = "multipart/form-data", onsubmit = "javascript:return checkfile(document.getElementById('fileAuthorization'))" }))
       {%>

之前叫做Submit button Onclick

<input type="submit" id="btnSave" name="btnSave" value="Upload" onclick="javascript:return checkfile(document.getElementById('fileAuthorization'))" />

我已经纠正了,它正在工作(验证和文件上传提交按钮点击和文件上传控制更改)。

但我的问题是为什么return false不工作提交按钮点击?但它的工作为Fileupload onchange事件

重定向发生的原因。在将同一行更改为MVC表单后,它开始工作(重定向现在没有发生)为什么?

将提交更改为:

<button type="button" id="btnSave" name="btnSave" onclick="checkfile(document.getElementById('fileAuthorization'))" ></button>

它不会自动提交表单

当你准备好提交表单时,你可以在javascript的回调函数中这样做:

document.getElementById('form-id').submit();