How to add required validator to ajax AsyncFileUpload?

試著忘記壹切 提交于 2020-01-14 14:42:07

问题


How to add client side required validator to asyncfileupload ,to enforce user to select file before submitting the page.


回答1:


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



回答2:


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>


来源:https://stackoverflow.com/questions/2983909/how-to-add-required-validator-to-ajax-asyncfileupload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!