如果文件已经存在,jQuery拦截并阻止表单提交

时间:2011-09-07 17:57:04

标签: asp.net asp.net-mvc asp.net-mvc-3 jquery

我使用的是MVC3,我有一个带文件上传的表单。如果该文件已存在于服务器上,我想提示用户确认是否要覆盖该文件。我已经在表单提交上添加了一个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>

所以我的问题是,我做错了什么?另外,作为奖励,如果客户端验证发现错误,有没有办法防止这种情况出现?

任何帮助将不胜感激!!!

更新 我最终做到了这一点,这适用于我想要做的事情。

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

3 个答案:

答案 0 :(得分:2)

问题是您的Ajax请求在提交处理程序完成之后才可能完成; ergo,帖子继续,你失去了取消它的能力。听起来你需要的是一扇门;基本上,直到你将标志设置为允许,你不能提交。像这样:

 var fileInvalid = true;
 $('#file').change(function()
 {
     $.getJSON('@Url.Action("CheckIfFileExists")', { path: filePath },
            function (exists) {
                if (exists) {
                    var cancel = confirm('File "' + filePath + '" has already been uploaded. Overwrite?');
                    if (cancel) {
                        fileInvalid = false;
                    }
                }
                else
                {
                    fileInvalid = false;
                }
            }
        );
 });

 $('#formUpload').submit(function(e)
 {
     if(fileInvalid)
        e.preventDefault();
 });

答案 1 :(得分:1)

我认为你真正想要的是远程验证:

http://deanhume.com/Home/BlogPost/mvc-3-and-remote-validation/51

答案 2 :(得分:1)

这是一种方法。除非已设置标志,否则基本思想是始终取消表单提交。如果文件不存在或用户确认提交,我们将标志设置为true,然后重新提交表单。

<script type="text/javascript" language="javascript">
    $(document).ready(function () {
        var $form = $('#formUpload');
        $form.submit(function (e) {
            // if user already confirmed, then let form submit
            if ($form.data('confirmed')) {
                return true;
            }
            // otherwise, prevent form submission so we can do file check
            e.preventDefault();
            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) {
                            // user wants to submit, so set flag and re-submit form
                            $form.data('confirmed', true).submit();
                        }
                    } else {
                        // the file doesn't exist, so we can force submission w/out the dialog
                        $form.data('confirmed', true).submit();
                    }
                }
            );
        });
    });
</script>