我使用MVC3,並且我有一個帶有文件上傳的表單。如果該文件已經存在於服務器上,我想提示用戶確認他們要覆蓋該文件。我已經在表單提交上添加了一個jQuery方法來處理我在線閱讀的內容,但是似乎郵件在初始化之前可以顯示確認對話框。如果文件已經存在,jQuery攔截並阻止表單提交
如果我在頂部調用e.preventDefault()
我的表單提交函數會停止表單,但是我不知道如何重新激活該操作。這裏是我有:
表單
@using (Html.BeginForm("Upload", "Management", FormMethod.Post, new {id = "formUpload", enctype = "multipart/form-data"})) {
<div class="editor-label">Pricing Model Workbook</div>
<div class="editor-field">
<input type="file" name="file" id="file" size="50" />
@Html.ValidationMessageFor(file => file.FileName)
</div>
<div><input type="submit" name="upload" id="upload" value="Upload" /></div>
}
jQuery的
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#formUpload').submit(function (e) {
var filePath = $('#file').val();
$.getJSON('@Url.Action("CheckIfFileExists")', { path: filePath },
function (exists) {
if (exists) {
var cancel = confirm('File "' + filePath + '" has already been uploaded. Overwrite?');
if (cancel) {
e.preventDefault();
return false;
}
}
return true;
}
);
});
});
</script>
所以我的問題是,我究竟做錯了什麼?此外,作爲獎勵,如果客戶端驗證發現錯誤,是否有任何方法可以防止這種情況出現?
任何幫助將不勝感激!
UPDATE 我最終這樣做,這對我正在嘗試做的工作。
<script type="text/javascript" language="javascript">
$(document).ready(function() {
var fileInvalid = false;
// check if file exists when user selects a new file
$('#file').change(function() {
var filePath = $('#file').val();
$.getJSON('@Url.Action("CheckIfFileExists")', { path: filePath },
function (exists) {
if (exists) {
var overwrite = confirm('Warning :: File "' + filePath + '" has already been uploaded.'
+ 'The existing data will be overwritten on submission. Continue?');
if (!overwrite) {
$('#file').replaceWith($('#file').clone(true));
}
}
}
);
});
});
</script>
只是擡起頭來,你仍然有一個競爭條件。如果用戶在文件檢查返回之前提交表單,用戶將永遠看不到對話框。 – jmar777