gpt4 book ai didi

javascript - 使用 Javascript 函数阻止 MVC 表单提交

转载 作者:行者123 更新时间:2023-11-28 16:02:02 27 4
gpt4 key购买 nike

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

upload.ascx 包含文件上传 控件。文件上传控件将上传 .xlsx 和 .xls 文件。我添加了 Java script 函数来执行此验证(以防止上传不必要的文件)。

FileUpload控件的OnchangeSubmit按钮的Onclick将调用相同的Validation函数。

文件上传验证功能适用于两种调用。如果用户单击提交按钮,则会调用相同的函数并且工作正常。

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

我已将调试器保留在我的操作结果中,如果文件错误(正确),则不会调用该调试器。如果文件正确,索引文件将加载成功消息(操作结果被调用并且工作正常)。 .

我怀疑MVC Form。如果上传了错误的文件,则在未调用操作结果的情况下发生重定向,这应该停止。

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

我的 upload.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'))"

这应该在 Form 标签本身中这样调用:

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

但之前它被称为“提交”按钮 Onclick

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

我已更正并开始工作(提交按钮 Onclick 的验证和文件上传和文件上传控件 onchange)。

但是我的问题是为什么return false在提交按钮点击时不起作用?但它适用于 Fileupload onchange 事件。

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

关于javascript - 使用 Javascript 函数阻止 MVC 表单提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16672336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com