Solved

Update javascript var on UpdatePanel update

Posted on 2011-09-30
8
363 Views
Last Modified: 2012-06-27
I have a GridView which is located within an UpdatePanel. Each row of the GridView has an image button rendered within it. I have implemented the ability to filter the datasource for the GridView to allow for searching.

I have a javascript function which evaluates the innerHTML of a particular cell within the GridView and prompts the user to confirm their selection. Upon clicking the row's image button, the javascript confirmation dialog is displayed, referencing the evaluated cell's innerHTML. This works great with the initial set of records displayed wtihin the GridView; however, upon filtering/paging through the GridView, the javascript confirmation continues to reference the original innerHTML that was in the GridView cell at the time of the last postback. Because of the UpdatePanel there is no Postback initiated when the GV is filtered or paged.

Is there a way I can get the javascript function to "re-evaluate" the cell values/its variables upon GridView filter/page? Code attached
0
Comment
Question by:alright
  • 4
8 Comments
 
LVL 12

Expert Comment

by:jagssidurala
Comment Utility
you need to execute your script function as below in search button.

ScriptManager.RegisterStartupScript(this, this.GetType(), "NewWindow", "<script type=\"text/javascript\"> Your script function </script>", false);
0
 

Author Comment

by:alright
Comment Utility
Which function would I want to call though? During which script function it is actually "caching" the table's contents I am unsure about.. and would this be the right structure?

ScriptManager.RegisterStartupScript(this, this.GetType(), "NewWindow", "<script type=\"text/javascript\">getGridViewControl()</script>", false);


Some further info; upon first load of the page, the GridView displays all of the datasource's rows. If I filter the list BEFORE clicking the image button for the first time, the javascript references the correct email/company names from the freshly filtered list. If I then re-filter or un-filter the list, the javascript continues referencing the email/companies that were present upon first click of the image button that is executing the Notify() function

Thanks for your help
0
 
LVL 22

Expert Comment

by:Mrunal
Comment Utility
you can attach or bind click event to image button in aspx / design page itself.
Better way use jQuery for this.

And add this code:

$(document).ready(function() {
        $("#IDOFIMAGE").live('click', function (e) {
         
            // Call function from here which
            // evaluates the innerHTML of a particular cell within the GridView

             return false;
        });
});

.live function of jQuery will bind click event to image button always until application is closed or externally click event is unbind.

this solution is for attaching event to single image button with ID.
If you want to attach click event to image buttons on all rows in gridview then :
1. Add cssclass / class to image button
2. instead of line in above code:
 $("#IDOFIMAGE").live('click', function (e) {
write:
 $(".CLASSNAMEOFIMAGE").live('click', function (e) {

Hope this solves your problem.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 

Author Comment

by:alright
Comment Utility
I'm sorry, I don't think I am explaining myself clearly.

The issue is not with adding a click handler to the imagebutton, that is already taken care of. I have included full example code below. Please consider the following situation.

Please run the example below after creating the SQL Table (tblExample) and inserting the appropriate values (pic included). You will be presented with a text box and a button. The button will filter the GridView's datasource's name field based on the textbox's contents.

Each GridView row contains an imagebutton (no image, so just text that says 'click me').

Click this text, you will be presented with a dialog box asking if you want to send an email to [name] at [email]. This works great! Looks good! Ok. Now filter the listing. For example, type 'jane' in the textbox and click Filter. Now click the imagebutton (click me). The javascript dialog box will still reference the ORIGINAL innerHTML values of the given row, i.e.:

Load the project. Click row 4's 'click me' button. The dialog box will read 'Are you sure you wish to send a notification email to jane at jane@smith.com?'. Click OK or Cancel, whichever.

Type 'jane' into the textbox and click Filter. Click row 1 of the filtered GridView's 'click me' button. The dialog box will read 'Are you sure you wish to send a notification email to john at john@smith.com?' when it SHOULD READ 'Are you sure you wish to send a notification email to jane at jane@smith.com?'

If you take out the updatepanel everything works fine, but I would very much like to keep the panel. How can I get the javascript to reference the proper innerHTML values AFTER a filter event?

I really hope this makes sense.

Thank you in advance. Points upped
CREATE TABLE [dbo].[tblExample](
	[id] [int] IDENTITY(1,1) NOT NULL,
	[name] [varchar](100) NULL,
	[email] [varchar](100) NULL
) ON [PRIMARY]



<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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">
<script type="text/javascript"">

    var gridViewCtlId = "GridView1";
    var gridViewCtl = null;
    var curSelRow = null;
    var curRowIdx = -1;

    function getGridViewControl() {
        if (null == gridViewCtl) {
            gridViewCtl = document.getElementById(gridViewCtlId);
        }
    }

    function onGridViewRowSelected(rowIdx) {
        var selRow = getSelectedRow(rowIdx);
        if (null != selRow) {
            curSelRow = selRow;
            var cellValue = getCellValue(rowIdx, 0);
            alert(cellValue);
        }
    }

    function getSelectedRow(rowIdx) {
        return getGridRow(rowIdx);
    }

    function getGridRow(rowIdx) {
        getGridViewControl();
        if (null != gridViewCtl) {
            return gridViewCtl.rows[rowIdx];
        }
        return null;
    }

    function getGridColumn(rowIdx, colIdx) {
        var gridRow = getGridRow(rowIdx);
        if (null != gridRow) {
            return gridRow.cells[colIdx];
        }
        return null;
    }

    function getCellValue(rowIdx, colIdx) {
        var gridCell = getGridColumn(rowIdx, colIdx);
        if (null != gridCell) {
            return gridCell.innerHTML;
        }
        return null;
    }

    function Notify(rowindex2) {
        name = getCellValue(rowindex2, 1);
        email = getCellValue(rowindex2, 2);
        if (confirm("Are you sure you wish to send a notification email to " + name + " at " + email + "?")) {
            return true;
        }
        else {
            return false;
        }
    }
</script>
    <title>Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        Example page<br />
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <br />
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                <asp:Button ID="Button1" runat="server" Text="Filter" />
                <br />
                <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
                    DataSourceID="SqlDataSource1" EnableModelValidation="True">
                    <Columns>
                        <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" 
                            ReadOnly="True" SortExpression="id" />
                        <asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
                        <asp:BoundField DataField="email" HeaderText="email" SortExpression="email" />
                        <asp:TemplateField HeaderText="button">
                            <ItemTemplate>
                                <asp:ImageButton ID="ImageButton1" runat="server" AlternateText="click me" 
                                    onclick="ImageButton1_Click" onprerender="ImageButton1_PreRender" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <br />
                <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
                <br />
                <br />
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
                    FilterExpression="[name] like '%{0}%'" 
                    SelectCommand="SELECT * FROM [tblExample]">
                    <FilterParameters>
                        <asp:ControlParameter ControlID="TextBox1" ConvertEmptyStringToNull="False" 
                            Name="newparameter" PropertyName="Text" />
                    </FilterParameters>
                </asp:SqlDataSource>
            </ContentTemplate>
        </asp:UpdatePanel>
        <br />
    
    </div>
    </form>
</body>
</html>







using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }

    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        GridViewRow row;
        ImageButton ib;
        string name;
        string email;

        ib = (ImageButton)sender;
        row = (GridViewRow)ib.NamingContainer;

        name = (string)(GridView1.Rows[row.RowIndex].Cells[1].Text.ToString());
        email = (string)(GridView1.Rows[row.RowIndex].Cells[2].Text.ToString());

        Label1.Text = "E-mail sent to " + name + " at " + email;
    }

    protected void ImageButton1_PreRender(object sender, EventArgs e)
    {
        GridViewRow gvr;
        ImageButton imgbtn;

        imgbtn = (ImageButton)sender;
        gvr = (GridViewRow)imgbtn.NamingContainer;

        imgbtn.Attributes.Add("onclick", "javascript:return Notify(" + (Convert.ToInt32(gvr.RowIndex.ToString()) + 1) + ");");
    }
}

Open in new window

tblExample.png
0
 

Accepted Solution

by:
alright earned 0 total points
Comment Utility
Adding:


gridViewCtl = null;

to the Notify() function has solved my issue. i.e.,

    function Notify(rowindex2) {
        gridViewCtl = null;
        name = getCellValue(rowindex2, 1);
        email = getCellValue(rowindex2, 2);
        if (confirm("Are you sure you wish to send a notification email to " + name + " at " + email + "?")) {
            return true;
        }
        else {
            return false;
        }
    }
0
 

Author Closing Comment

by:alright
Comment Utility
Thank you everyone who provided input
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Have you tried to learn about Unicode, UTF-8, and multibyte text encoding and all the articles are just too "academic" or too technical? This article aims to make the whole topic easy for just about anyone to understand.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now