Domanda

In una pagina che ho:

<asp:TextBox runat="server" ID="EmailTextBox" AutoPostBack="true" OnTextChanged="EmailTextBox_Changed" />
<asp:Button runat="server" ID="SearchButton" OnClick="AddButton_Click" Text="add" />

In EmailTextBox_Changed, conta su quanti messaggi possono essere trovati, prima di eseguire la ricerca.

Il problema è che, quando si digita qualcosa in EmailTextBox, e fare clic sul pulsante, è necessario fare clic due volte per ottenere i risultati effettivi in ??su. Questo perché il primo scatto sta facendo la parte "AutoPostBack" dalla casella di testo, e quindi è necessario fare clic di nuovo a fare il clic postback reale per accadere.

Senza rimuovere il "AutoPostBack = true", come posso fermarlo bisogno di due scatti in queste circostanze?

È stato utile?

Soluzione 3

che lo rende un controllo lato client è stata la soluzione a questo ... non sembra essere un modo per evitare che altrimenti

Altri suggerimenti

Ero alla ricerca di una risposta a questo problema pure. Ho finito per la rimozione di tutti AutoPostBack = true e facendo tutte le azioni con JavaScript, come te.

Tuttavia, una delle cose che ho sperimentato prima che il JavaScript era qualcosa da mantenere la concentrazione controllo dopo un postback. Ho notato che il campo nascosto che ho usato per memorizzare il nome del controllo che aveva l'ultima messa a fuoco ha avuto il nome del pulsante di ricerca (il mio è un pulsante Salva). Così, mentre non sono ancora sicuro di come ottenere la funzione 'ricerca' a fuoco 'automaticamente' come dovrebbe, che è sostanzialmente quella catena di eventi di postback sia dalla casella di testo e il pulsante insieme uno dopo l'altro, posso sapere che l'utente ha cliccato il pulsante Salva prima del postback è accaduto (o tentato di).

Quindi, quello che hai sul postback è il vostro fuoco evento di testo, e quindi il metodo Page Load, o qualsiasi altra cosa che si desidera utilizzare, in cui è possibile controllare per vedere che l'ultimo controllo per avere attenzione si è concentrata metodo ciclo di pagina. Con questo, ci sono diversi modi si potrebbe implementare un lavoro in giro.

Disattiva parte, si potrebbe aggiungere il codice in ogni evento che viene generato da un AutoPostBack di controllo, come la casella di testo e il pulsante di ricerca, per verificare il nome del controllo del fuoco. Se il controllo che ha avuto attenzione ultima non è la funzione AutoPostBack del controllo ci sono in esecuzione, possiamo impostare un bool livello di pagina chiamata 'Run_Controls_Method' TRUE, altrimenti, impostarla su false. In questo modo sappiamo che dovremmo eseguire il controllo che aveva ultimo metodo di messa a fuoco postback.

Il caricamento della pagina, si potrebbe fare qualcosa di simile:

if (Run_Controls_Method && hdfFocusControl.Value != "")
{
    switch(hdfFocusControl.Value)
    {
        case "btnSearch":
           btnSearch_OnClick(null, null);
           break;
        case etc.
    }
}

Il mio modo di attuare la hdfHasFocus è:

HTML:

<input id="hdfHasFocus" runat="server" type="hidden" />
codice

HTML dietro:

protected void Page_PreRender(object sender,EventArgs e)
{
   if (IsPostBack != true)
   {
       //Add the OnFocus event to all appropriate controls on the panel1 panel.         
       ControlManager.AddOnFocus(this.Controls,hdfHasFocus,true);
       //other code...
   }

   ControlManager.SetFocus(this.Controls,hdfHasFocus.Value,true);
}

ControlManager.cs relativo codice:

        /// <summary>
    /// Adds the onfocus event to the UI controls on the controls in the passed in control list.
    /// </summary>
    /// <param name="controls">The list of controls to apply this event.</param>
    /// <param name="saveControl">The control whose .value will be set to the control.ID of the control which had focus before postback.</param>
    /// <param name="Recurse">Should this method apply onfocus recursively to all child controls?</param>
    public static void AddOnFocus(ControlCollection controls, Control saveControl, bool Recurse)
    {
        foreach (Control control in controls)
        {
            //To make the .Add a bit easier to see/read.
            string action = "";

            //Only apply this change to valid control types. 
            if ((control is Button) ||
                (control is DropDownList) ||
                (control is ListBox) ||
                (control is TextBox) ||
                (control is RadDateInput) ||
                (control is RadDatePicker) ||
                (control is RadNumericTextBox))
            {
                //This version ignores errors.  This results in a 'worse case' scenario of having the hdfHasFocus field not getting a 
                //   value but also avoids bothering the user with an error.  So the user would call with a tweak request instead of 
                //   and error complaint.
                action = "try{document.getElementById(\"" + saveControl.ClientID + "\").value=\"" + control.ClientID + "\"} catch(e) {}";

                //Now, add the 'onfocus' attribute and the built action string.
                (control as WebControl).Attributes.Add("onfocus", action);
            }

            //The 'onfocus' event doesn't seem to work for checkbox...use below.
            if (control is CheckBox)
            {
                //This version ignores errors.  This results in a 'worse case' scenario of having the hdfHasFocus field not getting a 
                //   value but also avoids bothering the user with an error.  So the user would call with a tweak request instead of 
                //   and error complaint.
                action = "try{document.getElementById(\"" + saveControl.ClientID + "\").value=\"" + control.ClientID + "\"} catch(e) {}";
                //In case there is already an attribute here for 'onclick' then we will simply try to add to it.
                action = action + (control as WebControl).Attributes["onclick"];

                //Now, add the event attribute and the built action string.                 
                (control as WebControl).Attributes.Add("onclick", action);
            }

            //You don't seem to be able to easily work the calendar button wiht the keyboard, and it seems made for
            //  mouse interaction, so lets set the tab index to -1 to avoid focus with tab.
            if (control is CalendarPopupButton)
            {
                (control as WebControl).Attributes.Add("tabindex", "-1");
            }

            //We also want to avoid user tab to the up and down spinner buttons on any RadNumericTextBox controls.
            if (control is RadNumericTextBox)
            {
                (control as RadNumericTextBox).ButtonDownContainer.Attributes.Add("tabindex", "-1");
                (control as RadNumericTextBox).ButtonUpContainer.Attributes.Add("tabindex", "-1");
            }

            //Recursively call this method if the control in question has children controls and we are told to recurse.
            if ((Recurse) && (control.HasControls()))
            {
                AddOnFocus(control.Controls, saveControl, Recurse);
            }
        }
    }

    /// <summary>
    /// Searches the ControlCollection passed in for a match on the ID name string passed in and sets focus on that control if it is found.
    /// </summary>
    /// <param name="controls">The collection of controls to search.</param>
    /// <param name="FocusToID">The ID of the control to set focus on.</param>
    /// <param name="recurse">Recursively search sub-controls in the passed in control collection?</param>        
    /// <returns>True means keep processing the control list.  False means stop processing the control list.</returns>
    public static bool SetFocus(ControlCollection controls, string FocusToID, bool recurse)
    {
        //Return if no control ID to work with.
        if (string.IsNullOrEmpty(FocusToID) == true)
        { return false; }

        //If we get here and don't have controls, return and continue the other controls if applicable.
        if (controls.Count <= 0)
        { return true; }

        foreach (Control control in controls)
        {
            //If this is the control we need AND it is Enabled, set focus on it.
            if (((control is GridTableRow) != true) &&  //GridTableRow.ClientID throws an error. We don't set focus on a 'Row' anyway.
                (control.ClientID == FocusToID) && 
                ((control as WebControl).Enabled))
            {
                control.Focus();
                //return to caller.  If we were recursing then we can stop now.
                return false;
            }
            else
            {
                //Otherwise, see if this control has children controls to process, if we are told to recurse.
                if ((recurse) && (control.HasControls()))
                {
                    bool _continue = SetFocus(control.Controls, FocusToID, recurse);
                    //If the recursive call sends back false, that means stop.
                    if (_continue != true)
                    { return _continue; }
                }
            }
        }

        //We are done processing all the controls in the list we were given...
        //  If we get here, then return True to the caller.  If this was a recursive call, then
        //  the SetFocus in the call stack above will be told to continue looking since we 
        //  didn't find the control in question in the list we were given.
        return true;
    }

In realtà, non è necessario cliccare sul pulsante per fare il primo evento accada. Basta 'congedo' la casella di testo, vale a dire con 'tabulazione' fuori di esso per rendere l'AutoPostBack accadere.

Se si vuole fare entrambe le cose in una sola postback semplicemente rimuovere il pulsante e fare le cose che si fanno in AddButton_Click anche in caso Textbox_Change.

Scrivi sotto il codice nell'evento Page Load per prevenire il doppio clic

BtnSaveAndPrint.Attributes.Add("onclick", "return confirm('Are you sure you Want to Save & Print?');")

Si potrebbe evitare questo non farlo lato server e utilizzando Javascript. Inoltre, non ha fatto pubblicare il tuo evento di caricamento della pagina. Stai controllando se inviare di nuovo o no?

Un altro modo si potrebbe fare questo è l'evento che accade sul clic del pulsante può essere chiamato dall'evento TextChanged e sbarazzarsi del tasto tutti insieme.

Ho avuto lo stesso problema, ho deciso di spostare il codice evento click per l'evento di caricamento della pagina ed eseguirlo in caso di postback. E non utilizzare un evento click a tutti.

protected void Page_Load(object sender, System.EventArgs e)
    {
        if (IsPostBack)
        {
             // put code here
        }
    }

invece che:

public void ButtonClick(object sender, EventArgs e)
    {
      //...
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top