Friday, November 21, 2008

How to call Javascript after pageLoad Within UpdatePanel Like ClientScript...

Hi Every Body..

Today we are here to discuss really a vary interesting topic. You will enjoy it and it is vary usefull in several conditions.
How to call Javascript after some processing in Codebehind when we are in a update panel You know. clientscript is not working with update panel and master Page. So ummm.. there is problem. after a long googleing and some RnD finally I got the sloution.
The step for solution is geiven Below...

1.) On HTML page write the follwing line of code in java script


function load() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(testfunction);
}
In above "testfunction" is our java script function which we want to call in C# code after some processing within an Update Panel.

2.)
write the function as below:
function testfunction()
{
var i=0;
var ctrl = document.getElementById('ctl00_ContentPlaceHolder1_hid');
// Where ctl00_ContentPlaceHolder1_hid is an hiden field which is used to get updated value from code behind.
if(ctrl.value!="Some Condition")
{
// here Put your code which you want after page load..
}

}


3.)Now move to Code Behind...C# File of the page

on Page LoadEvent
protected void Page_Load(object sender, EventArgs e)
{
imgButton.Attributes.Add("onload", "load()");
// Do your Coding as per requirment...
}

4.) Look in to Click Event of the "imgButton" button

protected void imgButton_Click(object sender, ImageClickEventArgs e)
{
hid.Value=""; // Vocate the hidden field if it has some value ie. used to call script.
// do Your coding as per the requirment
If(Condtion)// The condtion on which you want to call java script..
{
//Update the value of the hidden field "hid"
hid.Value ="Your Comment as per the Condition";
}
else
{
hid.Value="";// again Vocate the hidden field...
}
imgButton.Attributes.Clear();// To prevent call script again and again.
//It is Esential.Please note that

}

5.) In the same way You can call script whenever you want just by repeating this process



Enjoy surfing our blog..

Sanjeev Kumar /Mahesh Sharma
On behalf of HelpOnDesk Team

No comments: