Click here to Skip to main content
15,891,633 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 181.1K   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

 
GeneralRe: My vote of 5 Pin
csharpbd13-Jul-13 21:08
professionalcsharpbd13-Jul-13 21:08 
QuestionI dont know where to include your solution Pin
leoivix4-Jul-13 1:55
leoivix4-Jul-13 1:55 
AnswerRe: I dont know where to include your solution Pin
csharpbd4-Jul-13 18:09
professionalcsharpbd4-Jul-13 18:09 
GeneralMy vote of 4 Pin
HariPrasad katakam24-Jun-13 3:37
HariPrasad katakam24-Jun-13 3:37 
GeneralMy vote of 4 Pin
Sumanth M17-Jun-13 20:16
Sumanth M17-Jun-13 20:16 
GeneralMy vote of 5 Pin
kamrulTalukdar17-Jun-13 5:19
kamrulTalukdar17-Jun-13 5:19 
GeneralRe: My vote of 5 Pin
csharpbd17-Jun-13 5:36
professionalcsharpbd17-Jun-13 5:36 
SuggestionCoolest Article ! Pin
Mushfiq Shishir5-Jun-13 18:45
Mushfiq Shishir5-Jun-13 18:45 
Thanks for such a nice article !
It would save a lot of times of many developers ! Smile | :) Smile | :) Smile | :)
GeneralRe: Coolest Article ! Pin
csharpbd5-Jun-13 18:49
professionalcsharpbd5-Jun-13 18:49 
GeneralMy vote of 5 Pin
Mushfiq Shishir5-Jun-13 18:43
Mushfiq Shishir5-Jun-13 18:43 
GeneralRe: My vote of 5 Pin
csharpbd5-Jun-13 18:48
professionalcsharpbd5-Jun-13 18:48 
GeneralMy vote of 5 Pin
ims.sanjay5-Jun-13 0:49
ims.sanjay5-Jun-13 0:49 
GeneralRe: My vote of 5 Pin
csharpbd5-Jun-13 6:44
professionalcsharpbd5-Jun-13 6:44 
QuestionSome issues to resolve... Pin
gstolarov4-Jun-13 19:03
gstolarov4-Jun-13 19:03 
GeneralMy vote of 5 Pin
Vince P.4-Jun-13 9:28
Vince P.4-Jun-13 9:28 
GeneralRe: My vote of 5 Pin
csharpbd4-Jun-13 10:07
professionalcsharpbd4-Jun-13 10:07 
GeneralMy vote of 5 Pin
Motahar Hossain3-Jun-13 17:53
professionalMotahar Hossain3-Jun-13 17:53 
GeneralRe: My vote of 5 Pin
csharpbd3-Jun-13 18:36
professionalcsharpbd3-Jun-13 18:36 

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.