Solved

Update javascript var on UpdatePanel update

Posted on 2011-09-30
8
365 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
ID: 36895411
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
ID: 36911982
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
ID: 36946762
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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 

Author Comment

by:alright
ID: 36964683
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
ID: 36981588
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
ID: 37010567
Thank you everyone who provided input
0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

803 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