【问题标题】:Prevent AsyncPostBackTrigger if value in the textbox is not valid如果文本框中的值无效,则阻止 AsyncPostBackTrigger
【发布时间】:2016-12-15 16:47:41
【问题描述】:

我的触发器中有以下代码:

<asp:AsyncPostBackTrigger ControlID="InitPay" EventName="TextChanged" />

而我的控件看起来像:

    <label class="ccsp">Initial Payment</label><br />
    <asp:TextBox ID="InitPay"  AutoPostBack="true" runat="server" OnTextChanged="InitPay_TextChanged" Style="width: 300px;">
    </asp:TextBox><b>$</b><br /> 
    <asp:CustomValidator ID="ValInitPay" ControlToValidate="InitPay" runat="server" ClientValidationFunction="Val_InitPay" OnServerValidate="ValInitPay_ServerValidate" ErrorMessage="Out of range error." Display="Dynamic"></asp:CustomValidator>

jQuery 验证函数:

function Val_InitPay(source, args) {
        if (Math.floor($('#InitPay').val()) == ($('#InitPay').val()) && $.isNumeric($('#InitPay').val())) {
            if ($('#InitPay').val() > ($("#InitPaymnet").val()) && $('#InitPay').val() < 1000)
            {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
            }
        }
        else {
            args.IsValid = false;
        }
    }

而验证函数背后的代码是:

protected void ValInitPay_ServerValidate(object source, ServerValidateEventArgs args)
    {
            if (int.TryParse(InitPay.Text, out val))
            {
                if (val > 10 && val < 1000)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                    ValInitPay.ErrorMessage = "<img  src='images/err_msg.png' height='11px' width='11px' style='vertial-align:middle' />Out of range";
                }
            }
            else
            {
                args.IsValid = false;
                ValInitPay.ErrorMessage = "<img  src='images/err_msg.png' height='11px' width='11px' style='vertial-align:middle' />Not an integer";
            }

    }

现在,当我在文本框中输入无效输入时,它会迅速触发触发功能。它给出了错误,但随后触发了触发器。有没有办法在值无效时停止触发器?

谢谢!

【问题讨论】:

    标签: c# asp.net validation webforms


    【解决方案1】:

    如果您在所有代码路径中使用 jQuery 的 e.preventdefault() 函数,我们可以确保输入无效,然后我们可以停止服务器跳闸。代码将如下所示

    function Val_InitPay(source, args) {
        if (Math.floor($('#InitPay').val()) == ($('#InitPay').val()) && $.isNumeric($('#InitPay').val())) {
            if ($('#InitPay').val() > ($("#InitPaymnet").val()) && $('#InitPay').val() < 1000)
            {
                args.IsValid = true;
            }
            else {
                args.IsValid = false;
                e.preventdefault()
            }
        }
        else {
            args.IsValid = false;
            e.preventdefault()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 2016-08-02
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      相关资源
      最近更新 更多