Stop postback on TextChanged

后端 未结 5 1620
鱼传尺愫
鱼传尺愫 2021-01-13 17:26

I have a textbox in an aspx page that has a TextChanged event attached to it. I also have a validator attached to the textbox.

When the text is changed, the validate

相关标签:
5条回答
  • 2021-01-13 17:36

    Add CausesValidation="true" for the text box and it will be good. If the validation is not valid there won't be any post-back.

    <asp:TextBox ID="txtQuantity" runat="server" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged" CausesValidation="true"></asp:TextBox>
    

    0 讨论(0)
  • 2021-01-13 17:50

    You can move validation to client side adding EnableClientScript="true" attribute. Postback won't occur as check will be performed with JS.

    Other than that you can check whether page is valid when performing callback function for TextChanged event so that to define whether function can proceed. You should add ValidationGroup attribute to your validator and call Page.Validate function specifying that group before Page.IsValid is checked.

    Upd

    Here's the tip.

    Add your own JS function, e.g.:

    function IsValid( args ) {
            if( args.value.length == 0 ) {
                return false;
            }
            else {
                return true;
            }
        }
    

    In Page_Load event add this code:

    txtQuantity.Attributes[ "onchange" ] = "if ( IsValid(this) == false ) return;";
    

    This won't mess up auto postback when input is correct, but will prevent postback otherwise.

    0 讨论(0)
  • 2021-01-13 17:50

    Just sharing an inline, shorter version of the accepted answer:

    <asp:TextBox ID="txtQuantity" runat="server"
        AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"
        onchange="if (this.value.length == 0) return;"></asp:TextBox>
    

    Having the same problem with a RequiredFieldValidator, the above worked for me.

    Known nag: the designer complains that "onchange" is not a valid server-side attribute.

    0 讨论(0)
  • 2021-01-13 17:51

    try it after change AutoPostBack="true" as AutoPostBack="false"..

    0 讨论(0)
  • 2021-01-13 17:56

    What I do is in my client validation function I test the event type I am in. If the event shows me in a change event, I claim the validation passed and leave.

    		if (event.type === 'change') {
    			args.IsValid.true;
          return;
    		}

    I believe this is the best solution as you can leave the validator wired up and the textbox set as you like and no longer worry about the change event causing the validation.

    0 讨论(0)
提交回复
热议问题