Calling JavaScript Function From CodeBehind Calling JavaScript Function From CodeBehind asp.net asp.net

Calling JavaScript Function From CodeBehind


You may try this :

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


C# to JavaScript: you can register script block to run on page like following:

ClientScript.RegisterStartupScript(GetType(),"hwa","alert('Hello World');",true);

replace alert() part with your function name.

For calling C# method from JavaScript you can use ScriptManager or jQuery. I personally use jQuery. You need to decorate the method that you want to call from JavaScript with WebMethod attribute. For more information regarding calling C# method (called PageMethod) from jQuery you can refer to Dave Ward's post.


Calling a JavaScript function from code behind

Step 1 Add your Javascript code

<script type="text/javascript" language="javascript">    function Func() {        alert("hello!")    }</script>

Step 2 Add 1 Script Manager in your webForm and Add 1 button too

Step 3 Add this code in your button click event

ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "Func()", true);