需要在ASP.NET中自动提交文本框后两次点击按钮

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中键入内容并单击按钮时,需要点击两次才能获取实际结果。这是因为第一次点击正在执行文本框的"AutoPostBack"部分,然后必须再次单击才能发生实际的点击回发。

在不删除"AutoPostBack=true"的情况下,如何在这些情况下停止需要两次单击?


将按钮从服务器控件更改为基于客户端的按钮,并使用JS实现。 - JonH
6个回答

2
我也在寻找解决方法,最终我移除了所有autopostback=true并使用了JavaScript执行所有操作,就像你一样。
然而,在使用JavaScript之前,我尝试过一种方式来保持控件焦点在postback后。我注意到我用来存储上一个焦点控件名称的隐藏字段确实有搜索按钮的名称(我的是保存按钮)。因此,虽然我仍然不确定如何使“搜索”函数像应该一样“自动”触发,即将文本框和按钮的postback事件链接在一起,但我可以知道用户在postback发生之前(或尝试之前)点击了保存按钮。
因此,在postback时,你会触发文本框事件,然后是Page_Load方法或者你想要使用的任何页面生命周期方法,你可以检查上一个焦点控件是什么。有了这个,你可以实现几种解决方法。
举个例子,你可以在每个autopostback控件事件中添加代码,比如文本框和搜索按钮,来检查焦点控件的名称。如果上一个焦点控件不是我们正在运行的控件的autopostback函数,我们就可以设置一个名为“Run_Controls_Method”的页面级布尔变量为TRUE,否则,将其设置为false。这样,我们就知道应该运行上一个焦点控件的postback方法。
在页面加载时,你可以做以下事情:
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;
    }

1
在Page_Load事件中编写以下代码以防止重复点击。
BtnSaveAndPrint.Attributes.Add("onclick", "return confirm('Are you sure you Want to Save & Print?');")

1
实际上,您不必点击按钮即可发生第一个事件。 只需“离开”文本框,即通过“制表符”使AutoPostBack发生。

如果您想在单个PostBack中同时执行两者,请删除按钮,并在Textbox_Change事件中执行AddButton_Click中的操作。


嗯,也许吧。我想尝试避免这种情况,因为文本框只进行计数,而按钮则进行完整的获取。 - Paul

1
将其变为客户端检查是解决此问题的方法...否则似乎没有其他防止它的方式。

0

我曾经遇到过同样的问题,我决定将点击事件代码移动到页面加载事件中,在回发的情况下执行它。而且根本不使用点击事件。

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

改为:

public void ButtonClick(object sender, EventArgs e)
    {
      //...
    }

0

你可以避免这种情况,不要在服务器端处理,而是使用Javascript。你也没有发布你的页面加载事件。你是否检查了它是否回传?

另一种方法是,在单击按钮时发生的事件可以从TextChanged事件中调用,并完全摆脱按钮。


嗯,我考虑过这个问题。实际上有更多的文本框,并且自动提交已经启用,这样你可以在筛选结果时看到数量,当你准备好时,可以显示它们。也许完全使用JavaScript的解决方案是前进的道路。 - Paul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接