RegisterStartupScript() on Page_Unload

A

Amir Tohidi

Hi

I am trying to inject a piece of JavaScript into my pages (using the
MasterPage).

I need to send the session time out value to the client (the code is below).
Whilst I can step into the Page_Unload() method and see the script get
registered, I can not see the script in the pages source file once it has
appeared in the browser.

Anyone see what I am doing wrong?

Thanks



public partial class MasterPage : System.Web.UI.MasterPage
{
string TIMEOUT_SCRIPT =
@"<script language=""JavaScript"">
<!--
setTimeout(""timedOut()"", ###);

function timedOut()
{

document.getElementById('TimeoutLabel1').style.visibility = 'visible';
}
// -->
</script>";

protected void Page_Load(object sender, EventArgs e)
{
// Update the version label
LabelVersionInfo.Text = "JHAdmin version:" +
Assembly.GetExecutingAssembly().GetName().Version;
}

protected void Page_Unload(object sender, EventArgs e)
{
//this.SessionTimeoutControl1.Foo();

// Calculate the number of seconds to time out
int timeOutInSeconds = Page.Session.Timeout * 60 * 1000;
string numberOfSeconds = timeOutInSeconds.ToString();

// Put the script on the page that will make the label visible once
the session has timed out
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey",
TIMEOUT_SCRIPT.Replace("###", numberOfSeconds));

}
}
 
M

Milosz Skalecki [MCAD]

Hi Amir,

Page_Unload is too late as the page content has already been rendered to the
outgoing stream. Use Page_PreRender, or override OnRender method:

1. PreRender:
protected void Page_PreRender(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey",
TIMEOUT_SCRIPT.Replace("###", numberOfSeconds));

}

2. If PreRender is too early, try to override Render method

protected override void Render(HtmlTextWriter writer)
{
// you have to do it before calling Render() of the base class
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptKey",
TIMEOUT_SCRIPT.Replace("###", numberOfSeconds));

base.Render(writer);
}


Hope this helps
 
A

Amir Tohidi

Hi Milosz

You were right: I put the code in PreRender and everything is working jsut
right.

Thanks for your help
Amir
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top