问题描述:

I have a simple page with an UpdatePanel and two buttons:

<asp:Button ID="Button1" runat="server" ClientIDMode="Static" Text="Search" OnClick="UpdateSearchResults" />

<asp:UpdatePanel ID="UpdatePanel1" runat="server" ClientIDMode="Static" UpdateMode="Conditional" ChildrenAsTriggers="false">

<ContentTemplate>

<asp:Button ID="Button2" runat="server" ClientIDMode="Static" Text="Search" OnClick="UpdateSearchResults" />

<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />

<asp:AsyncPostBackTrigger ControlID="Button2" EventName="Click" />

</Triggers>

</asp:UpdatePanel>

Clicking either button should run "UpdateSearchResults" on the server, which renders content into the placeholder. Clicking either button manually works as espected - so far so good.

However, if I use jQuery to trigger the button click for Button2 programmatically, e.g.

$("Button2").click();

then the partial postback never happens, whereas it does if I do exactly the same thing to Button1.

I've tried:

  • Substituting .click() with .trigger('click')
  • Setting ChildrenAsTriggers to true
  • Selecting the button using ClientID

all to no avail. So what's going on here? Why can I trigger the click event of one button but not the other?

网友答案:

Your mistake is that you are missing the # sign in start of selector which specifies to use Id selector, and it is not guaranted that after control renders it will have the Button2 as client side id on the browser unless you set ClientIDMode to Static, but i will not recomment to do that.

The better way is to use the ClientID Property of the Control which will cause compile time errors in future if you remove the button or change it's name, using magic strings will fail your client side code :

$('#<%= Button2.ClientID %>').click();
相关阅读:
Top