簡體   English   中英

防止使用Javascript功能提交MVC表單

[英]Prevent MVC form submit using Javascript Function

我的項目中有一個upload.ascx 它將被加載到Jquery Popup內部。

upload.ascx包含File Upload控件。 文件上載控件將上載.xlsx and .xls文件。 我添加了Java script功能來進行此驗證(以防止上傳不必要的文件)。

Onchange of FileUpload控件的Onchange of FileUploadOnclick of Submit buttonOnclick of Submit button將調用相同的Validation函數。

文件上傳驗證功能可同時用於兩個調用。 如果用戶單擊提交按鈕,則將調用相同的功能,並且可以正常工作。

我的問題是:在我的驗證函數中,我編寫了return false 顯示警報消息后,頁面將被重定向到某個URL( localhost/Admin/Authorization/AcceptFile.aspx )。 AcceptFile是我的ActionResult名稱。 它不應該發生。 該函數返回False。 但是為什么表單被重定向到上方URL。

我將調試器保留在我的操作結果中,如果錯誤的File(正確),調試器不會被調用。 如果其文件正確,索引文件將加載成功消息(正在調用操作結果並可以正常工作)。

我懷疑是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;
    }

我的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表單后,其正常工作(現在不發生重定向)為什么?

將您的提交更改為此:

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

而且它不會自動提交表單

當您准備好提交表單時,可以在回調函數中使用javascript進行提交:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM