12

私が持っているページ:

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

EmailTextBox_Changedでは、検索を実行する前に、検出できる電子メールの数をカウントします。

問題は、EmailTextBoxに何かを入力してボタンをクリックすると、実際の結果を取得するために2回クリックする必要があることです。これは、最初のクリックでテキストボックスから「AutoPostBack」の部分が実行され、次にもう一度クリックして実際のクリックポストバックを実行する必要があるためです。

「AutoPostBack=true」を削除せずに、このような状況で2回クリックする必要がないようにするにはどうすればよいですか。

4

6 に答える 6

2

私もこの問題に対する答えを探していました。私はあなたと同じように、すべてのautopostback = trueを削除し、JavaScriptを使用してすべてのアクションを実行することになりました。

ただし、JavaScriptの前に実験したことの1つは、ポストバック後にコントロールのフォーカスを維持することでした。最後のフォーカスDIDを持つコントロールの名前を格納するために使用した非表示フィールドに検索ボタンの名前があることに気付きました(私のものは保存ボタンです)。したがって、「検索」機能を「自動的に」起動する方法はまだわかりませんが、基本的には、テキストボックスとボタンの両方からのポストバックイベントを次々にチェーンすることですが、それを知ることができますポストバックが発生する(または実行しようとする)前に、ユーザーがその保存ボタンをクリックしました。

したがって、ポストバックにあるのは、テキストボックスイベントの発生、次にPage_Loadメソッド、または使用するページサイクルメソッドです。ここで、フォーカスを持っている最後のコントロールが何であるかを確認できます。これにより、回避策を実装する方法がいくつかあります。

一方で、テキストボックスや検索ボタンなど、コントロールのオートポストバックから発生するすべてのイベントにコードを追加して、フォーカスコントロールの名前を確認することもできます。最後にフォーカスがあったコントロールが、実行しているコントロールの自動ポストバック関数ではない場合は、「Run_Controls_Method」というページレベルのブール値をTRUEに設定できます。それ以外の場合は、falseに設定します。このようにして、ラストフォーカスポストバックメソッドを持つコントロールを実行する必要があることがわかります。

ページの読み込み時に、次のようなことができます。

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

hdfHasFocusを実装する方法は次のとおりです。

HTML:

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

背後にあるHTMLコード:

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関連コード:

        /// <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;
    }
于 2010-12-16T16:24:16.193 に答える
1

実際、最初のイベントを発生させるためにボタンをクリックする必要はありません。テキストボックスを「残す」だけです。つまり、「タブ」を付けて、AutoPostBackを実行します。

1つのポストバックで両方を実行する場合は、ボタンを削除し、Textbox_ChangeイベントでもAddButton_Clickで実行することを実行します。

于 2010-07-06T18:22:34.870 に答える
1

それをクライアント側のチェックにすることがこれに対する解決策でした...そうでなければそれを防ぐ方法はないようです

于 2010-10-22T10:57:00.057 に答える
1

2回クリックされないように、Page_Loadイベントに以下のコードを記述します

BtnSaveAndPrint.Attributes.Add("onclick", "return confirm('Are you sure you Want to Save & Print?');")
于 2014-12-05T04:04:27.743 に答える
0

サーバー側で実行せず、Javascriptを使用することで、これを回避できます。また、ページ読み込みイベントを投稿していません。ポストバックするかどうかチェックしていますか?

これを行う別の方法は、ボタンのクリックで発生するイベントをTextChangedイベントから呼び出して、ボタンをまとめて削除することです。

于 2010-07-06T18:23:42.297 に答える
0

同じ問題が発生しました。クリックイベントコードをページ読み込みイベントに移動し、ポストバックの場合に実行することにしました。また、クリックイベントはまったく使用しないでください。

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

それ以外の :

public void ButtonClick(object sender, EventArgs e)
    {
      //...
    }
于 2013-09-17T14:59:01.247 に答える