還有其他一些方法可以使用表單對象的DefaultButton屬性或面板的DefaultButton屬性來設置默認按鈕,但我發現它們在各種瀏覽器中過去不可靠,所以通常我依賴於javascript,if你不希望按鈕可見,你可以將visible屬性設置爲false。
這段代碼唯一的缺點是你必須關閉頁面指令的事件驗證,但它應該觸發點擊事件,並觸發驗證器和所有。
以下是我們使用的代碼示例。通常我會將註冊函數放在一個實用程序類中,但在本例中它是在頁面代碼中。
<%@ Page Language="C#" EnableEventValidation="false" %>
<script runat="server">
protected void cmdSubmit1_Click(object sender, EventArgs e)
{
litValue.Text = "Value 1 - You entered: " + txtValue1.Text;
}
protected void cmdSubmit2_Click(object sender, EventArgs e)
{
litValue.Text = "Value 2 - You entered: " + txtValue2.Text;
}
/// <summary>
/// This function registers what button is clicked based on whatever control currently has focus
/// so for example if the user password field has focus then you can cause the enter button to click
/// if the enter key is pressed This works with ie and firefox as far as I know
/// </summary>
/// <param name="ControlWithFocus"></param>
/// <param name="ControlToClick"></param>
private void RegisterDefaultButton(System.Web.UI.Control ControlWithFocus, System.Web.UI.Control ControlToClick)
{
PostBackOptions p = new PostBackOptions(ControlToClick);
p.PerformValidation = true;
if (ControlToClick is Button)
{
p.ValidationGroup = ((Button)ControlToClick).ValidationGroup;
}
else if (ControlToClick is ImageButton)
{
p.ValidationGroup = ((ImageButton)ControlToClick).ValidationGroup;
}
else if (ControlToClick is LinkButton)
{
p.ValidationGroup = ((LinkButton)ControlToClick).ValidationGroup;
}
p.RequiresJavaScriptProtocol = false;
AttributeCollection a = null;
if (ControlWithFocus is HtmlControl)
{
a = ((System.Web.UI.HtmlControls.HtmlControl)ControlWithFocus).Attributes;
}
else if (ControlWithFocus is WebControl)
{
a = ((System.Web.UI.WebControls.WebControl)ControlWithFocus).Attributes;
}
if (a != null)
{
a["onKeyDown"] = string.Format("if (event.keyCode == 13) {{{0}}}"
, ControlToClick.Page.ClientScript.GetPostBackEventReference(p));
}
}
protected void Page_Load(object sender, EventArgs e)
{
RegisterDefaultButton(txtValue1, cmdSubmit1);
RegisterDefaultButton(txtValue2, cmdSubmit2);
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
Enter Value 1: <asp:TextBox ID="txtValue1" runat="server"></asp:TextBox>
<br />
Enter Value 2: <asp:TextBox ID="txtValue2" runat="server"></asp:TextBox>
<br />
<asp:Literal ID="litValue" runat="server"></asp:Literal>
<asp:LinkButton ID="cmdSubmit1" runat="server" Visible="false" OnClick="cmdSubmit1_Click">Hidden Button 1</asp:LinkButton>
<input id="cmdSubmit2" runat="server" visible="false" type="button" value="Hidden Button 2" onserverclick="cmdSubmit2_Click" />
</form>
</body>
</html>