Monday, December 21, 2009

Calling function in code-behind using AJAX

Ever wanted to call a function in your code-behind using Javascript? I have. Maybe you want to do some client side functionality and then follow it up with some server side functionality, all without a post-back. The answer to doing this is using javascript, AJAX and the PageMethods functionality of the AJAX scriptmanager.

In order to call a function in code-behind, try this:

1. Create your AJAX web-enabled page and create a scriptmanager with your update panels, etc.
2. In the scriptmanager tag, set "EnablePageMethods" equal to True.
3. Create a javascript function using PageMethods to call the code-behind function.

     function UnlockRecord()
          {
               //Use the PageMethods functionality of the scriptmanager
               PageMethods.UnlockRecord();
          }

4. In your code-behind, create your function as a web services webmethod. 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.

     <System.Web.Services.WebMethod()> _
     Public Shared Function UnlockRecord() As String

          'Code to run

     End Function

That's all there is to it. Now all you have to do is call your javascript which in turn will call your code-behind function.

No comments: