I’ve got a textbox and a button in asp.net wrapped in an updatepanel like so:
<asp:UpdatePanel ID="UpdatePanel21" runat="server" UpdateMode="Always" >
<ContentTemplate>
<asp:TextBox ID="txtLIDescription" runat="server" Columns="50">
</asp:TextBox>
<asp:Button ID="btnAddLineItem" runat="server" onclick="btnAddLineItem_Click"
Text="Add" ToolTip="Add line item." UseSubmitBehavior="false" />
</ContentTemplate>
</asp:UpdatePanel>
If I click the button everything works as expected. But when I hit the enter key (which I think my users will do), the system seems to do a post back. I tried to avoid it using jquery:
$('#LineItemContent_txtLIDescription')
.livequery('keyup', function (event) {
if (event.keyCode == 13) {
$('#LineItemContent_btnAddLineItem').focus();
$('#LineItemContent_btnAddLineItem').click();
}
$("#LineItemContent_btnAddLineItem").button();
});
If I place an alert("hello world"); I see it has entered the if condition so it knows an enter has been clicked. Then I was hoping to set the focus to the button and then have it click the button, just like a regular end user would click the button. Nope seems to post back.
I tried adding:
event.preventDefault();
return false;
In the jquery hoping that will avoid it, nope same thing. I even tried ASP.net markup and added
UseSubmitBehavior=false
And the page still seems to be posting back. Is this due to it being inside an updatepanel? Is there any other way around this??
You could try to wrap the content of the
UpdatePanelin aPaneland set it’sDefaultButtonproperty tobtnAddLineItem.Edit: “The question is why does this work…”
First the cause of your issue: It’s not ASP.NET specific that the first button in a form will be clicked when you press enter key, that’s normal behaviour. But an UpdatePanel does an asynchronous postback only if the control that caused the postback is inside the UpdatePanel. Otherwise you need to specify an
AsyncPostBackTriggerexplicitely for that control.My approach works since it ensures that the appropriate button (inside the UpdatePanel) is clicked when the user clicks enter inside that Panel. This causes an asynchronous postback as desired.
This is not a hack but a useful feature introduced in ASP.NET 2.0. Your code keeps being readable, you don’t need to use “javascript hacks”.