Multiple Ways to Call Javascript Function from CodeBehind in ASP.Net

Multiple Ways to Call Javascript Function from CodeBehind:



JavaScript is one of the very versatile scripting languages that are used in Web applications. Even though we can accomplish everything in server side programming using C#, it is still advisable to do some of the things like validations, etc in clientside using JavaScript. In ASP.Net 1.x, we don’t have that much support in the framework to hook JavaScript functions from the asp.net page dynamically. This drawback was addressed with the release of ASP.Net 2.0 by providing developers a lot many features to embed JavaScript blocks dynamically through a class called ClientScriptManager.


ClientScriptManager Class:


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 .NetFramework 1.x version, there is no class that helps us to handle this situation effectively. This drawback was addressed .NetFramework 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.



 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 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 hence similar scripts are avoided. This will avoid the confusion caused when we are adding scripts from usercontrols. For example, the method IsClientScriptBlockRegistered() can be used for checking duplicate script 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.



Examples related to gridview:


Comments

Popular posts from this blog