我也在寻找解决方法,最终我移除了所有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)
{
ControlManager.AddOnFocus(this.Controls,hdfHasFocus,true);
}
ControlManager.SetFocus(this.Controls,hdfHasFocus.Value,true);
}
ControlManager.cs 相关的代码:
public static void AddOnFocus(ControlCollection controls, Control saveControl, bool Recurse)
{
foreach (Control control in controls)
{
string action = "";
if ((control is Button) ||
(control is DropDownList) ||
(control is ListBox) ||
(control is TextBox) ||
(control is RadDateInput) ||
(control is RadDatePicker) ||
(control is RadNumericTextBox))
{
action = "try{document.getElementById(\"" + saveControl.ClientID + "\").value=\"" + control.ClientID + "\"} catch(e) {}";
(control as WebControl).Attributes.Add("onfocus", action);
}
if (control is CheckBox)
{
action = "try{document.getElementById(\"" + saveControl.ClientID + "\").value=\"" + control.ClientID + "\"} catch(e) {}";
action = action + (control as WebControl).Attributes["onclick"];
(control as WebControl).Attributes.Add("onclick", action);
}
if (control is CalendarPopupButton)
{
(control as WebControl).Attributes.Add("tabindex", "-1");
}
if (control is RadNumericTextBox)
{
(control as RadNumericTextBox).ButtonDownContainer.Attributes.Add("tabindex", "-1");
(control as RadNumericTextBox).ButtonUpContainer.Attributes.Add("tabindex", "-1");
}
if ((Recurse) && (control.HasControls()))
{
AddOnFocus(control.Controls, saveControl, Recurse);
}
}
}
public static bool SetFocus(ControlCollection controls, string FocusToID, bool recurse)
{
if (string.IsNullOrEmpty(FocusToID) == true)
{ return false; }
if (controls.Count <= 0)
{ return true; }
foreach (Control control in controls)
{
if (((control is GridTableRow) != true) &&
(control.ClientID == FocusToID) &&
((control as WebControl).Enabled))
{
control.Focus();
return false;
}
else
{
if ((recurse) && (control.HasControls()))
{
bool _continue = SetFocus(control.Controls, FocusToID, recurse);
if (_continue != true)
{ return _continue; }
}
}
}
return true;
}