Tags

, , , , ,

Problem?

While working in combination with jQuery/JavaScript and ASP.NET WebForms control UpdatePanel, you will find out that after you trigger UpdatePanel for updating, your jQuery/JavaScript code doesn’t work anymore.

Why is this happening?

UpdatePanel replaces the content with the result returned from the server. This means all hooked events previously will not work after a post back.

Solution #1

Use

Sys.Application.add_load(name_of_your_function);

inside of your UpdatePanel .

Example:

jQuery/JavaScript function

<script type="text/javascript">
    function clickMe() {
        $("#btnClick").click(function () {
            alert("Done!");
        });
    }
</script>

ASP.NET with UpdatePanel and using part of re-call code mentioned above in Solution #1 paragraph

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
        <%-- calling jQuery/JS after Updatepanel postback --%>
            <script type="text/javascript" language="javascript">
                Sys.Application.add_load(clickMe);
            </script>
            <asp:Button ID="btnClick" runat="server"
            OnClick="btnClick_Click" Text="Click" />
        </ContentTemplate>
     </asp:UpdatePanel>

This will call jQuery/JavaScript on asynchronous post back.

Solution #2
With help of jQuery you can use jQuery.on() function which allows us to attach an event handler for one or more events to the selected elements.

Example with our above javascript event:

<script type="text/javascript">
$('body').on('click', '#btnClick', function () {
            alert('Done!');
        });
</script>

jQuery.on() function will attach an event handler to selected element even if it doesn’t exist. That is the main purpose of this function. This function helps with situations, if we are dynamically adding our elements on the page for example with jQuery.append() or like in our case after UpdatePanel destroys event handlers on post back.

Advertisements