Registering a script multiple times

In the code behind, I am registering the script to run like below:

  string strFunctionName = "ShouldAdd";
  sb.Append(strFunctionName + @"((blnShouldAdd ? "true" : "false") + ", true);");

  ScriptManager.RegisterStartupScript(this, this.GetType(), "shouldAdd", sb.ToString(), true);

      

This piece of code is called twice, once on Page Load when blnShouldAdd

evaluating as false

and in the button's event handler when blnShouldAdd

evaluating as true

.

Oddly enough, when I debug the code and enter the ShouldAdd JS function, the value is always false. I would assume this is true, since the second call in the event handler overrides the first.

Any ideas?

0


a source to share


3 answers


I think you should use the IsStartupScriptBlockRegistered()

or method IsClientScriptBlockRegistered()

to check if the script has been added and only bother RegisterStartupScript

when it returns false

.



+1


a source


The reason why you need to pass complex parameters "this" and "this.GetType ()" to the function RegisterStartupScript()

is to make sure that the given function is registered only once. This way your code runs once, not twice.



+1


a source


The page load is also done when you click the button, as part of the asp.net page lifecycle, and is triggered before the button's event handler. So, when you get to the button event handler, you've already registered the script with Page Load, so the request to register another script with the same (type, key) pair is ignored.

Perhaps you should move the call from the Load page to a later point in the pag lifecycle, perhaps PreRender in a better place.

+1


a source







All Articles