简体   繁体   中英

jQuery intercept and prevent form submission if file already exists

I using MVC3 and I have a form with a file upload. If the file already exists on the server, I want to prompt the user to confirm that they want to overwrite the file. I have added a jQuery method on the form submit to handle this from what I've read online, but it seems like the post is being intialized before it can display the confirm dialog..

If I call e.preventDefault() at the top of my form submit function it stops the form, but then I don't know how to reinvoke the action. Here is what I have:

The Form

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

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

So my question is, what am I doing wrong? Also, as a bonus, is there any way to prevent this from popping up if the clientside validation catches an error?

Any help would be greatly appreciated!!!

UPDATE I ended up doing this and this works for what I was trying to do.

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

The problem is that your Ajax request doesnt potentially complete until after the submit handler is finished; ergo, the post continues and you lose the ability to cancel it. It sounds like what you need is a gate; basically, until you set the flag as allowable, you can't submit. Something like so:

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

I think what you really want is remote validation:

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

Here's one approach. The basic idea is to always cancel form submission, unless a flag has been set. We set the flag to true if either the file didn't exist, or the user confirmed submission, and then re-submit the form.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM