简体   繁体   中英

DropDownList Postback on ENTER Keypress Not Firing the Server-Side Event

Greetings!

I have a simple navigation menu consisting of an asp:DropDownList and an asp:Button. Users select an item from the dropdown and click the button to go to the new URL. I'd like to be able to able to support when users hit the ENTER key when a dropdown list item is selected so that it replicates the behavior as if they've clicked the button.

Here's what I have thus far:

<asp:DropDownList ID="ddlMenu"
                  runat="server"
                  onkeypress="if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {__doPostBack('GoButton',''); return false;}" />

<asp:Button ID="btnGoButton" runat="server" onclick="GoButton_Click"/>

The button's click code is:

protected void GoButton_Click(object sender, EventArgs e)
{
    string l_url = ddlMenu.SelectedItem.Value;
    Response.Redirect(l_url);
}

However, everytime I hit the ENTER key, the page posts back but the button's client event handler doesn't fire. Am I missing something?

have your tried wrapping your controls in a panel with the default button? I know it works for textboxes

<asp:Panel runat="server" id="searchPanel" DefaultButton="btnGoButton">
    <asp:DropDownList ID="ddlMenu" runat="server" />
    <asp:Button ID="btnGoButton" runat="server" onclick="GoButton_Click"/>
</asp:Panel>

Well, you are using the wrong button id.

The ID in the __doPostBack method must be the UniqueID of the trigger control. You say the trigger is 'GoButton', but it has the ID 'btnGoButton'.

There is no way for the server to know that your 'GoButton' actually is the btnGoButton.

Also remember that name mangling (a method to ensure unique names for controls) may mess up the UniqueID even more.

Try to write like this instead: __doPostBack('<%# btnGoButton.UniqueID %>', '');

or append it in the codebehind..

ddlMenu.Attributes.Add("onkeypress", string.Format("__doPostBack('{0}', '');", btnGoButton.UniqueID);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM