Textbox asp.net postback trigger twice on autopost

2020-05-03 13:26发布

问题:

On textbox OnTextChanged event the postback cycle triggering twice. Breakpoints on both methods to understand the issue. Here is my code sample

<form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="TextBox1" OnTextChanged="TextBox1_TextChanged" AutoPostBack="true" />
    </div>
    <asp:Label ID="Label1" runat="server"></asp:Label>
</form>

Its code behind.

     public static int cycle { get; set; }
     protected void Page_Load(object sender, EventArgs e)
     {

     }
     protected void TextBox1_TextChanged(object sender, EventArgs e)
     {
        cycle++;
        Label1.Text = cycle.ToString(); 
     }

回答1:

Avoid using AUTOPOSTBACK, keep the OnTextChanged event trap and add a button (hidden or not) to catch the return pression on the textbox to produce the POSTBACK.

Here is an example

        <asp:Panel runat="server" CssClass="col-md-2">
            <asp:Panel runat="server" CssClass="form-group input-group" DefaultButton="BTN_Cerca">
                <span class="input-group-btn">
                    <asp:Button runat="server" ID="BTN_Cerca" Text="Codice" CssClass="btn btn-secondary" ToolTip="Cerca in magazzino"/>
                </span>
                <asp:TextBox runat="server" ID="TXT_Search" CssClass="form-control" placeholder="Numero Articolo" OnTextChanged="TXT_Search_TextChanged" />
            </asp:Panel>
        </asp:Panel>