Friday, 27 May 2016

How to call Javascript function from ASP.Net, C# code behind

There are multiple ways of calling Javascript functions from code behind C#. This can be done by using ClientScriptManager Class which is introduced in .NetFreamework 2.0.

ClientScriptManager Class is used to create the scripts in HTML dynamically. This class has set of methods to accomplish the requirements based on the situation.

Often, we use the below two methods for many of our ASP.Net applications.

  • RegisterClientScriptBlock() Method
  • RegisterStartupScript()

RegisterClientScriptBlock() Method

ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
{
    script.RegisterClientScriptBlock(this.GetType(), "Alert", "alert('hi')",true);
}

RegisterStartupScript() Method

ClientScriptManager script = Page.ClientScript;
if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert"))
{
    script.RegisterStartupScript(this.GetType(), "Alert", "alert('hi')",true);
}

Both the methods, RegisterStartupScript() and RegisterClientScriptBlock() inject Javascript code that will be execute during page load or start up of subsequent postback. The main difference is that RegisterClientScriptBlock() methods injects the script after the form open tag ("< form >") but before page controls and the RegisterStartupScript() methods injects the script after page controls but before form close tag ("< /form >"). That means using RegisterClientScriptBlock() method, we cannot access page controls in the script block while using RegisterStartupScript() method we can.

We can also directly call the Javascript functions available in the page as show below.

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","MyFunction()",true);

MyFunction() is the function of Javascript in HTML. CallMyFunction is the string of ClientScriptmanager Class which is unique to avoid duplicated functions

Here is the example for Javascript confirm alert in C# -

Page.ClientScript.RegisterStartupScript(this.GetType(),"CallMyFunction","return confirm('Are you sure to continue?')",true);


No comments:

Post a Comment