We normally add JavaScript functions to our webpage using
<Script> tag. There are situations where we need to add the scripts
dynamically from the codebehind class. In .NET Framework 1.x version, there is
no class that helps us to handle this situation effectively. This drawback was
addressed in .NET Framework 2.0 by introducing a new class called ClientScriptManager.
This class can be used to manage and add script blocks to the asp.net page from
codebehind class.
Things we should know about ClientScriptManager Class
·
ClientScript property of the Page object
will give us an instance of ClientScriptManager object. We can add the scripts
dynamically through this instance which will be then be injected in the HTML
output.
·
This class uniquely identifies scripts by a key String and a
Type. Scripts with the same key and type are considered duplicates and similar
scripts are then avoided. This will avoid the confusion caused when we are
adding scripts from user controls. For example, the method
IsClientScriptBlockRegistered() can be used for checking duplicate scripts
registered for RegisterClientScriptBlock() method.
ClientScriptManager class has a set of useful methods which
we can use to inject the JavaScript functions in the HTML output. We can choose
to use these methods to accomplish our requirements depending on the situation.
This part of the article will discuss the usages of 3
different methods.
1.
RegisterClientScriptBlock() Method
2.
RegisterStartupScript() Method
3.
RegisterOnSubmitStatement() Method