开发者

popup dialog on submit

开发者 https://www.devze.com 2023-03-22 14:07 出处:网络
I have a partial view in MVC2: <%@ Control Language=\"C#\" Inherits=\"System.Web.Mvc.ViewUserControl<dynamic>\" %>

I have a partial view in MVC2:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<div class="uploader">
    <form action="/media/uploader" method="post" enctype="multipart/form-data">
        <input id="File1" type="file" name="upfile" />
        <input type="submit" value="Upload" />
    </form>
</div>
enter code here

I dont know how to do next:

after user press submit button, I would like to validate extension of uploaded file. If extensio开发者_如何学运维n is valid, I would post uploaded file, but if extension is not suported, I would like to alert user somehow (popup?) and abort submit. I tried some things with jquery, but I just dont understand it enough so I cant make it work.

Thank you for any advice.


I'm not an MVC guy but I know that you have two options that should work here just from the strict JS/FORMS perspective...

The form has an event - onsubmit - if you have an event handler that returns false to the onsubmit event, the submit won't happen. Similarly, if you have an event handler on the submit button's onclick event, returning false will cancel the click, hence, the form post as well.

Here's an example relying on the form's onsubmit:

<form action="/myDir/myPage.ext" method="post" onsubmit="return validForm(window.event);">
 ....
</form>

If you implement the method validForm it might look something like:

    function validForm(e) {
        var fullPath = document.getElementById('File1').value;
        if (validateFileExtension(fullPath)) {
            return true;
        } else {
            alert('Invalid extension for this file!');
            return false;
        }
    }

    function validateFileExtension(fullPath) {
        var isValid = false;
        // some logic to parse and validate extension
        // if the logic passes, we set isValid to true.
        return isValid;
    }

With the above methods fully implemented, your two options are to use the method in either the submit button's onclick event or in the form's onsubmit event. Either way, you'll want to check the value of the File Input, ensure the extension is what you want, and return false if the extension violates whatever your business rules are. If you return true, the button click/form submit will proceed. If you return false, the form submit or button click (depending on which event you've wired to) will cancel - either way, same result - no form submission without what you want in the file field.

Happy coding.

B


You could use the Ajax Upload plugin which allows you to do this.

0

精彩评论

暂无评论...
验证码 换一张
取 消