Register ClientScriptBlock only once during multiple postbacks

426 Views Asked by At

In my asp.net websites I regular uses the following methods before actually adding either custom pieces of script or registering a js file:

IsClientScriptBlockRegistered(Type, String)

IsClientScriptIncludeRegistered(Type, String)

When a page requires a custom piece of script, somewhere during PageLoad I call IsClientScriptBlockRegisterd() followed by RegisterClientScriptBlock().

if (!Page.ClientScript.IsClientScriptBlockRegistered(typeof(Page), "myKey"))
{
  // Start creating ScriptBlock //
  // .. //

  // Actually Register the script //
  ToolkitScriptManager.RegisterClientScriptBlock(this, typeof(Page), "myKey", 
    sbScript.ToString(), false);
}

The above code is always called once during a postback.

When a user is on the related page, while staying on that page he can cause multiple postbacks (actual postbacks, not callbacks). During a postback the GetRegisteredClientScriptBlocks method always returns an empty collection. So IsClientScriptBlockRegistered always returns false. Therefore, for each postback I have to recreate the custom scriptblock and re-register it with the page, and re-send it to the client.

Is there a way to register a custom scriptblock and let it exist at the client for as long as the user stays on the related page, or for as long as the users sessions is active?

Thanks in advance.

1

There are 1 best solutions below

1
On

Assuming you are using ASP.Net WebForms, you may use the following property to ensure whether it is postback or not:

Page.IsPostback()

Alternatively, you may pass some sort of flag/cookie/hidden variable indicating that this particular page does not need any client scripts to be registered.