Calling JavaScript Function From CodeBehind

Can someone provide good examples of calling a JavaScript function From CodeBehind and Vice-versa?


Solution 1:

You may try this :

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

Solution 2:

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.