How to execute JavaScript Function From ASP.NET Code Behind

Waqas Anwar
06 January 2011
25117 Views

You have a JavaScript function and you want to execute it from ASP.NET code behind file. You can achieve this by using RegisterStartupScript method of ClientScript class as shown below:

Let's suppose you have following JavaScript function in your code.
<script type="text/javascript">

   function SayMeHello() {
      alert('Hello');
   }

</script>

In order to call it from code behind, use the following code
if (!ClientScript.IsStartupScriptRegistered("helloAlert"))
{
   Page.ClientScript.RegisterStartupScript(
      this.GetType(),
      "helloAlert",
      "SayMeHello();",
      true);
}