开发者

How to add required validator to ajax AsyncFileUpload?

开发者 https://www.devze.com 2023-01-02 16:55 出处:网络
How to add client side required validator 开发者_运维百科to asyncfileupload ,to enforce user to select file before submitting the page.You could also set the text of a the hidden textbox in a server s

How to add client side required validator 开发者_运维百科to asyncfileupload ,to enforce user to select file before submitting the page.


You could also set the text of a the hidden textbox in a server side method using C# or VB, rather than a client side Javascript or JQuery function.

    protected void afu_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
    {
        afu.SaveAs(Server.MapPath("Uploads\\") + e.FileName);

        txt.Text = e.FileName;       
    }


I use a RequiredFieldValidator that validates an invisible TextBox. The TextBox is filled with an arbitrary text in the OnClientUploadComplete function. The only thing you cannot is setting the focus when it is validated. The example uses jQuery.

<ajaxToolkit:AsyncFileUpload runat="server" ID="afu" ClientIDMode="AutoID" UploaderStyle="Traditional" OnClientUploadComplete="asyncUploadComplete" OnClientUploadStarted="asyncUploadStarted" />
<asp:RequiredFieldValidator runat="server" ID="rfv" ControlToValidate="txt" Text="The file is required!" SetFocusOnError="false" />
<asp:TextBox runat="server" ID="txt" style="display:none" MaxLength="0" />
<script type="text/javascript">
    // AsyncFileUpload - OnClientUploadComplete
    function asyncUploadComplete(sender, args) {
        // Assemble info of uploaded file
        var contentType = args.get_contentType();
        var info = args.get_length() + " bytes";
        if (contentType.length > 0) {
            info += " - " + contentType;
        }
        info += " - " + args.get_fileName();
        // Put info in the first input field after the AsyncFileUpload control
        var source = $(sender.get_element());
        source.nextAll('input').val(info);
        // Validate immediately
        ValidatorEnable(source.nextAll('span')[0], true);
    }
    // AsyncFileUpload - OnClientUploadStarted
    function asyncUploadStarted(sender, args) {
        // Clear the first input field after the AsyncFileUpload control
        var source = $(sender.get_element());
        source.nextAll('input').val('');
    }
</script>
0

精彩评论

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