Skip to main content

Call javascript function from codebehind in asp.net

Hello friends

 Today I am going to explain how to call JavaScript function from code behind without assigning it to any control in asp.net. Calling a JavaScript function from code behind is quiet simple, yet it confuses a lot of developers. First declare a JavaScript function in your code as shown below:



<script type="text/javascript">

        function SimpleAlert() {        
            // this will display a hello in alert box
            alert('hello')

        }
        function JavascriptWithParameter(msg) {         
            alert(msg)
        }
    </script>

Now we are going to call this JavaScript function in 2 ways from C# code behind

Way 1: Calling JavaScript function at page load

To call a JavaScript at page load we are going to use ScriptManager.RegisterStartupScript method this method accepts 5 parameters(To read more on this here is MSDN LINK) To call script use below code

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc", "SimpleAlert();", true);
            
            var message = "Hello from code using C#";
            //To pass parameter to javascript function
            System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "abc1", "JavascriptWithParameter('" + message + "');", true);

          
        }
    }
   
Here is main part  of syntax



Way 2: Calling JavaScript function on button click

To call a JavaScript on button click we are going to use ScriptManager. RegisterClientScriptBlock
Here this complete code

protected void Button1_Click(object sender, EventArgs e)
    {
        var message = "button 1 click call";   

        System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(System.Web.UI.Page), "showmsg1", "JavascriptWithParameter('" + message + "');", true);
    }



Comments