views:

50

answers:

3

Is it possible to call a C# function in my codebehind from javascript?

+4  A: 

Yes, you could use PageMethods.

Darin Dimitrov
Another link to the PageMethods... http://sappidireddy.wordpress.com/2008/03/31/how-to-call-server-side-function-from-client-side-code-using-pagemethods-in-aspnet-ajax/
Yves M.
Thanks @Darin. This looks like the way too go. I have one issue though, i'm getting a javascript error stating that PageMethods is not recognised. Could you think of something I am doing wrong?
Yo Momma
A: 

Remote Scripting - Use client-side JavaScript to remotely invoke methods in ASP.NET pages.

or

aspx page :

  <script language="javascript">

      function init()

      {

           alert('hello ');

           <%SetData();%>;

           alert('<%=strName%>');

      }

      </script>

Code behind file :

    public class _default : System.Web.UI.Page

    {

      public string strName = string.Empty;

      public void SetData()

      {

           strName = "dungla";

      }
 }
Pranay Rana
+1  A: 

You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.

Check this link

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX

Shoban
This is a copy of my answere here ;-) http://stackoverflow.com/questions/3994150/can-you-call-c-function-from-javascript/3994170#3994170
Shoban