Click here to Skip to main content
15,885,546 members
Articles / Web Development / ASP.NET

Working with jQuery within the ASP.NET UpdatePanel

Rate me:
Please Sign up or sign in to vote.
4.90/5 (41 votes)
7 Mar 2017CPOL2 min read 181K   2K   64   47
Working with jQuery and UpdatePanel in the same page.

Introduction

While developing an ASP.NET Webforms application, I've found that I couldn't use JQuery alongside UpdatePanel ! I've looked deeply into it and found that the partial PostBack of UpdatePanel was removing the JQuery Events. Then I've made numerous attempts to make it working the UpdatePanel alongside JQuery ! I've googled a lot and reviewed a lot's of blog post but was unable to find the exact output from there !! 

Lastly I've found a solution to it by myself!

To illustrate the procedure, I've made a demo project which has two fully functional pages. In Page1.aspx I've tried to add two numbers using JQuery and server side events. On the button '+' I've added two numbers from JQuery and on the button '+(*)' I've added two numbers from server side event. While the page1.aspx is loading, the JQuery event binding was occurred in document.Ready.

The partial postback prevents the jquery to work. In this solution I've overcome the problem. I've solved it by the endRequest event which is raised after an asynchronous postback is finished and control has been returned to the browser.  

Project Source Code:

Using the code  

In the project you will have two pages one is for jQuery not Working in Update Panel (Page1.aspx) and another is jQuery Working in Update Panel (Page2.aspx).

In Page1.aspx jquery doesn't work.

Image 1

In the + button will add two numbers using jquery and +(*) button will add two numbers using client side method. Here is the Page1.aspx code : 

XML
<%@ Page Language="C#" AutoEventWireup="true" 
    CodeBehind="Page1.aspx.cs" Inherits="jQuerywithinUpdatePanel.Page1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Page-1</title>

    <script src="js/jquery-1.7.2.min.js" 
         type="text/javascript"></script>

    <script type="text/javascript">
        //
        function IsValidNumber() {
            if ($(this).val() == "") {
                //$(this).val("0");
                alert("Please enter valid value!");
                $(this).focus();
            }
            else if ($.isNumeric($(this).val()) == false) {
                alert("Please enter valid value!");
                $(this).focus();
            }
        }

        function Add() {
            var Num1 = parseInt($('#txtNum1').val());
            var Num2 = parseInt($('#txtNum2').val());
            var Result = Num1 + Num2;
            $('#txtResult').val(Result);
        }

        $(document).ready(function() {
            $('#txtNum1').change(IsValidNumber);
            $('#txtNum2').change(IsValidNumber);
            $('#btnClientAdd').click(Add);
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="SM" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="upMain" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <div>
                <table>
                    <tr>
                        <td>
                            <input type="button" id="btnClientAdd" value=" + " />
                        </td>
                        <td>
                            <asp:TextBox ID="txtNum1" 
                                runat="server" Width="100px"></asp:TextBox>
                            +
                            <asp:TextBox ID="txtNum2" 
                                runat="server" Width="100px"></asp:TextBox>
                            =
                            <asp:TextBox ID="txtResult" 
                                 runat="server" Width="100px"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Button ID="btnServerAdd" runat="server" 
                                 Text=" +(*) " OnClick="btnServerAdd_Click" />
                        </td>
                    </tr>
                </table>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

 and Page1.aspx.cs code:  

C#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace jQuerywithinUpdatePanel
{
    public partial class Page1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnServerAdd_Click(object sender, EventArgs e)
        {
            int Num1 = Convert.ToInt16(txtNum1.Text);
            int Num2 = Convert.ToInt16(txtNum2.Text);
            int Result = Num1 + Num2;
            txtResult.Text = Result.ToString();
        }
    }
} 

Here, the two numbers are being added from JQuery every time I click on button '+'. But after clicking on server side event on button '+(*)' once, the JQuery event doesn't fire ! That was the problem to me !

The solution I've shown in Page2.aspx.

In Page2.aspx, I've used one more function to complete the JQuery event binding which works after the partial PostBack is occurred and binds the JQuery events on the document.Ready on pageEndRequest

Image 2

Here is the Page2.aspx code:

XML
<%@ Page Language="C#" AutoEventWireup="true" 
      CodeBehind="Page2.aspx.cs" Inherits="jQuerywithinUpdatePanel.Page2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Page-2</title>

    <script src="js/jquery-1.7.2.min.js" 
          type="text/javascript"></script>

    <script type="text/javascript">
        //
        function IsValidNumber() {
            if ($(this).val() == "") {
                //$(this).val("0");
                alert("Please enter valid value!");
                $(this).focus();
            }
            else if ($.isNumeric($(this).val()) == false) {
                alert("Please enter valid value!");
                $(this).focus();
            }
        }

        function Add() {
            var Num1 = parseInt($('#txtNum1').val());
            var Num2 = parseInt($('#txtNum2').val());
            var Result = Num1 + Num2;
            $('#txtResult').val(Result);
        }

        function InIEvent() {
            $('#txtNum1').change(IsValidNumber);
            $('#txtNum2').change(IsValidNumber);
            $('#btnClientAdd').click(Add);
        }

        $(document).ready(InIEvent);
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="SM" runat="server">
    </asp:ScriptManager>

    <script type="text/javascript">
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent);
    </script>

    <asp:UpdatePanel ID="upMain" 
           runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <div>
                <table>
                    <tr>
                        <td>
                            <input type="button" 
                              id="btnClientAdd" value=" + " />
                        </td>
                        <td>
                            <asp:TextBox ID="txtNum1" runat="server" 
                              Width="100px"></asp:TextBox>
                            +
                            <asp:TextBox ID="txtNum2" runat="server" 
                              Width="100px"></asp:TextBox>
                            =
                            <asp:TextBox ID="txtResult" 
                              runat="server" Width="100px"></asp:TextBox>
                        </td>
                        <td>
                            <asp:Button ID="btnServerAdd" runat="server" 
                                    Text=" +(*) " OnClick="btnServerAdd_Click" />
                        </td>
                    </tr>
                </table>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

and Page2.aspx.cs code: 

C#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace jQuerywithinUpdatePanel
{
    public partial class Page2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnServerAdd_Click(object sender, EventArgs e)
        {
            int Num1 = Convert.ToInt16(txtNum1.Text);
            int Num2 = Convert.ToInt16(txtNum2.Text);
            int Result = Num1 + Num2;
            txtResult.Text = Result.ToString();
        }
    }
}

Here, the pageEndRequest binds the JQuery events after the partial PostBack of UpdatePanel is occurred. Then the JQuery and server side both events are working perfectly !!

The PageRequestManager adds an endRequest for the document.Ready which enables the jQuery binding after partial postback and Jquery keeps still enabled. Please make sure to add those lines in aspx file  to enable jquery event binding which will do the trick for you ! 

XML
<script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent);
</script>

Hope it will save your time! 

Points of Interest   

jQuery is always interesting to work with but I've faced some critical problem while using UpdatePanel along with jQuery ASP.NET 3.5. After goggling so many times and going through so many articles I've come to this solution !

Reference 

I've found some help from here. You can check also this link.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader Enosis Solutions
Bangladesh Bangladesh
"passion", "excitement" and "learning"

Comments and Discussions

 
QuestionThanks Pin
CyberAngel28-Apr-21 3:22
CyberAngel28-Apr-21 3:22 
Questioncalling InIEvent method in document ready would need the Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InIEvent); code? Pin
Member 1367292011-Feb-18 7:40
Member 1367292011-Feb-18 7:40 
PraiseGreat solution Pin
Dragana Vukovic30-Nov-17 22:29
Dragana Vukovic30-Nov-17 22:29 
PraiseOMG Thank you sooooo much!! Pin
Member 1249365218-May-17 6:24
Member 1249365218-May-17 6:24 
QuestionGood Article Pin
Santhakumar M7-Jan-16 0:25
professionalSanthakumar M7-Jan-16 0:25 
AnswerRe: Good Article Pin
csharpbd5-Mar-16 7:35
professionalcsharpbd5-Mar-16 7:35 
GeneralRe: Good Article Pin
Santhakumar M6-Mar-16 7:29
professionalSanthakumar M6-Mar-16 7:29 
GeneralYou.. Pin
Taher Ahmed Taher18-Jul-15 8:59
Taher Ahmed Taher18-Jul-15 8:59 
GeneralRe: You.. Pin
csharpbd21-Jul-15 19:15
professionalcsharpbd21-Jul-15 19:15 
QuestionThanks you....Save my day. Pin
Arkadeep De8-Apr-15 18:14
professionalArkadeep De8-Apr-15 18:14 
AnswerRe: Thanks you....Save my day. Pin
csharpbd9-Apr-15 4:06
professionalcsharpbd9-Apr-15 4:06 
QuestionHow it does work when we have a master page ? Pin
Faisal Bora9-Mar-15 0:55
Faisal Bora9-Mar-15 0:55 
QuestionThank you! Pin
S Douglas1-Mar-15 7:16
professionalS Douglas1-Mar-15 7:16 
AnswerRe: Thank you! Pin
csharpbd1-Mar-15 16:55
professionalcsharpbd1-Mar-15 16:55 
QuestionThankFull Pin
Member 1143635917-Feb-15 0:29
Member 1143635917-Feb-15 0:29 
AnswerRe: ThankFull Pin
csharpbd17-Feb-15 19:22
professionalcsharpbd17-Feb-15 19:22 
Thank you.....
Questionmany many thanks Pin
ASalamBarket14-Oct-14 23:21
ASalamBarket14-Oct-14 23:21 
AnswerRe: many many thanks Pin
csharpbd15-Oct-14 5:30
professionalcsharpbd15-Oct-14 5:30 
QuestionGood tip Pin
Mike Hankey31-Aug-14 13:41
mveMike Hankey31-Aug-14 13:41 
AnswerRe: Good tip Pin
csharpbd31-Aug-14 20:00
professionalcsharpbd31-Aug-14 20:00 
GeneralMy vote of 5 Pin
Mushfiq Shishir6-Jun-14 9:37
Mushfiq Shishir6-Jun-14 9:37 
QuestionNice article! Pin
Mushfiq Shishir6-Jun-14 9:36
Mushfiq Shishir6-Jun-14 9:36 
AnswerRe: Nice article! Pin
csharpbd8-Jun-14 6:18
professionalcsharpbd8-Jun-14 6:18 
Questionthis is perfect Pin
Member 154512925-Apr-14 5:23
Member 154512925-Apr-14 5:23 
AnswerRe: this is perfect Pin
csharpbd28-Apr-14 10:16
professionalcsharpbd28-Apr-14 10:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.