Click here to Skip to main content
12,511,553 members (47,497 online)
Click here to Skip to main content
Add your own
alternative version

Stats

106.2K views
1.8K downloads
58 bookmarked
Posted

Working with jQuery within the ASP.NET UpdatePanel

, 13 Jun 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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.  

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.

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 : 

<%@ 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:  

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

Here is the Page2.aspx code:

<%@ 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: 

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 ! 

<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)

Share

About the Author

csharpbd
Software Developer (Senior) Codemen
Bangladesh Bangladesh
"passion", "excitement" and "learning"

You may also be interested in...

Pro
Pro

Comments and Discussions

 
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
Member 773191118-Jul-15 8:59
memberMember 773191118-Jul-15 8:59 
GeneralRe: You.. Pin
csharpbd21-Jul-15 19:15
membercsharpbd21-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
membercsharpbd9-Apr-15 4:06 
QuestionHow it does work when we have a master page ? Pin
Faisal Bora9-Mar-15 0:55
memberFaisal 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
membercsharpbd1-Mar-15 16:55 
QuestionThankFull Pin
Member 1143635917-Feb-15 0:29
memberMember 1143635917-Feb-15 0:29 
AnswerRe: ThankFull Pin
csharpbd17-Feb-15 19:22
membercsharpbd17-Feb-15 19:22 
Questionmany many thanks Pin
ASalamBarket14-Oct-14 23:21
memberASalamBarket14-Oct-14 23:21 
AnswerRe: many many thanks Pin
csharpbd15-Oct-14 5:30
membercsharpbd15-Oct-14 5:30 
QuestionGood tip Pin
Mike Hankey31-Aug-14 13:41
professionalMike Hankey31-Aug-14 13:41 
AnswerRe: Good tip Pin
csharpbd31-Aug-14 20:00
membercsharpbd31-Aug-14 20:00 
GeneralMy vote of 5 Pin
Mushfiq Shishir6-Jun-14 9:37
memberMushfiq Shishir6-Jun-14 9:37 
QuestionNice article! Pin
Mushfiq Shishir6-Jun-14 9:36
memberMushfiq Shishir6-Jun-14 9:36 
AnswerRe: Nice article! Pin
csharpbd8-Jun-14 6:18
membercsharpbd8-Jun-14 6:18 
Questionthis is perfect Pin
Member 154512925-Apr-14 5:23
memberMember 154512925-Apr-14 5:23 
AnswerRe: this is perfect Pin
csharpbd28-Apr-14 10:16
membercsharpbd28-Apr-14 10:16 
QuestionThanks Pin
Rockstar_20-Mar-14 0:30
professionalRockstar_20-Mar-14 0:30 
AnswerRe: Thanks Pin
csharpbd20-Mar-14 9:11
membercsharpbd20-Mar-14 9:11 
GeneralMy vote of 5 Pin
hamed74318-Feb-14 18:57
memberhamed74318-Feb-14 18:57 
GeneralMy vote of 5 Pin
Mihai MOGA13-Jul-13 20:56
professionalMihai MOGA13-Jul-13 20:56 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160929.1 | Last Updated 14 Jun 2013
Article Copyright 2013 by csharpbd
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid