Call JavaScript function from code behind in asp.net


Description:-

This article explains how to call JavaScript function from code behind in Asp.net C# on button click or based upon some condition. While developing asp.net application there are many times where we want to call a JavaScript function from C#, based on some business logic we do further logic etc. In Asp.net calling JavaScript function from code-behind c# after button click [server-side] is a quite easy code, as shown below.

First, we add an Asp.net Web form page in our project and write a JavaScript function on our .aspx page, here default.aspx is our newly added Web page.

Add a JavaScript function on default.aspx page under head tag, as later we want to call this JS function from code behind. Our simple JavaScript function alert method look like as written below.

Script:-

<script type="text/javascript" language="javascript">
        function helloWorld() {
            alert("welcome to aspcodder.info");
        }
</script>

Using the below-given code we able to call the javascript function from server-side.

Default.aspx.cs

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:helloWorld(); ", true);

Related Posts

Previous
Next Post »

Thanks for comments.....