ScriptManager.RegisterClientScriptBlock vs. ClientScript.IsStartupScriptRegistered
Why is it necessary to use the namespace- System.Web.Extensions- for ScriptManager.RegisterClientScriptBlock but not for ClientScript.IsStartupScriptRegistered. My understanding is that the former is AJAX based and the later isn't.
ParisPosted Mar 25, 2011, 4:56 PM
I personally recently solved an issue related to this...I had developed a custom validator control with client-side validation. For this, I had used Page.ClientScript.RegisterClientScriptBlock. The control worked perfectly on almost all cases: directly on a form, in the edit template of a gridview column, in formviews, etc, even inside an update panel in a form. However, when I added a gridview inside an update panel, with my custom validator only in the edit and insert templates, my javascript stopped working. If I added my custom control somewhere else within the same update panel, it would work again. The reason was this:
If my custom control was only inside the gridview's edit/insert templates, when the page loaded (with the grid in read-only mode) my control was not rendered and no script was posted anywhere. When I clicked "Edit" on the gridview, the control would be rendered as part of the partial (async) postback, but the page had already been rendered so it had no opportunity to post its client script anywhere. If I had my validator somewhere else within the update panel (visible always), then that always-visible instance would successfully register its script the first time that the page was loaded, so when the grid changed its view, the validator within it was able to find the script that had already been added by the other instance.
When I changed my custom control to register the client script with a ScriptManager, everything worked fine. That is because even with a partial update, the ScriptManager (which handles the update to begin with) is re-rendered, and thus it is capable of posting new stuff within itself. Hence, the registered code got emitted to the page, and everything worked.
In short, if code is supposed to be emitted to the page upon loading (or more typically pre-rendering) a control, but the said control is not loaded when the page is first rendered, but rather as part of anan AsyncPostBack, the Page.ClientScript.RegisterClientScriptBlock will not work and ScriptManager.RegisterClientScript is necessary. For most other cases, registering the script on the page will work. Generally, if you intend for your custom control to work within an update panel, you should provide some way to register its client-script within the scriptmanager, presumably reverting to registering with the Page if the script manager is not present or the control isn't within an update panel.
Craig DavisPosted Mar 23, 2011, 10:16 AM
Suthish NairPosted Mar 23, 2011, 9:41 AM