简体   繁体   中英

ASP/C# - UpdatePanel and Button OnClick Event Not Triggered

I've been trying to find the solution but it would be great if someone can take a look.

In my aspx page and C# codebehind I have the following:

aspx:

<asp:UpdatePanel runat="server" ID="UpdatePanel8" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="btnAddTableRow" EventName="Click" />
    </Triggers>
    <ContentTemplate>
        <div id="divDynamicFields" runat="server"></div>
    </ContentTemplate>
</asp:UpdatePanel>

<div hidden>
    <asp:Button ID="btnAddTableRow" runat="server" OnClick="AddTableRow" />
</div>

<script type="text/javascript">
    function addTableRow(tableId) {
        $('#<%=btnAddTableRow.ClientID%>').click();
    }
</script>

C#:

protected void AddTableRow(object sender, EventArgs e)
{
    (...)
}

The event is triggered if I don't use UpdatePanel, but when executed with UpdatePanel, there is PostBack but the C# method is not called. I've tried to understand it for some time with no avail. Any ideas? Thank you.

After a good night sleep and a fresh mind, I finally found out what is failing. The JS function addTableRow(tableId) is actually called by buttons that are dynamically created in Page_Load (the number of these buttons are not fixed, hence associating them with this JS function which clicks the hidden button that triggers the event method from codebehind). Problem is, I was generating these buttons in the following way:

Button addRowButton = new Button();
addRowButton.Text = "This is my dynamically generated button";
addRowButton.Attributes.Add("onclick", "addTableRow('" + idControl + "')");

But things started working when I've changed to:

HtmlGenericControl addRowButton = new HtmlGenericControl("input");
addRowButton.Attributes.Add("type", "button");
addRowButton.Attributes.Add("onclick", "addTableRow('" + idControl + "');");
addRowButton.Attributes.Add("value", "This is my dynamically generated button");

It's actually kind of strange, since the button created with Button() still invoked JS function addTableRows and caused PostBack but didn't invoke the code behind method. Perhaps it had to do with the page life cycle and the generated IDs for the dynamic buttons that are generated in different ways depending on creating them as Button or HtmlGenericControl, but in any ways it's working now.

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