Calling methods in a codebehind function (PageMethods) from client side using ajax.net

Hi,
    Everyone using ajax.net will be familiar with the updatepanels. In addition another well known way of utilizing the rich ajax.net library is calling web service methods or methods from the code behind file from the client side. Recently i came across a situation in my project where i wanted to call methods from code behind (i have been using updatepanels but in some situation all i was doing was getting few values from the db and i felt not using the updatepanel would be a better option rather calling the my code behind function using pagemethods feature would be more appropriate). Though  there is a good deal of information on the internet on update panels and calling web services i found it difficult to reach a good enough article showing me how to call a function from the codebehind file.  Finally though :-) i was able to call the code behind function. i am going to demonstrate the same in this blog.
   Before starting let me indicate there could be many reasons for calling code behind methods from client side using ajax.net .....in my case i wanted to use existing functionality in my code behind and we were not using any webservices .

   Here i am going to demonstrate a simple   application that calls a code behind method

to start first we create an ajax enabled website. Then in our page we add the heart of ajax.net -- the ScriptManager control and set the EnablePageMethods property as true

<ajax:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">

We also place a div and input buttons on our form

<div id="div1">

</div>

<input type="button" value="Call Page Method With No Parameters" onclick="CallPageMethod()" />

<input type="button" value="Call Page Method With Parameters" onclick="CallParametersPageMethod()" />

 

As the text indicates on call a function without parameters and the other calls a function having parameters

The code behind function are as below

[System.Web.Services.WebMethod()]
public static string MyFirstPageMethod()
{
  
return "Welcome to the world of AJAX.NET " ;
}


[System.Web.Services.
WebMethod()]
public static string MyFirstParameterPageMethod(String strVal)
{
   return "Welcome to the world of AJAX.NET , the value you passed is : " + strVal ;
}

To call a page method it must be static and you have to mark it with the WebMethod attribute. The first function doesnot takes parameter while the second function takes a string value as parameter. both return a string value.

 The javascript function are as below

<script language="javascript">

function CallPageMethod()
{
    PageMethods.MyFirstPageMethod(onSucceeded,onFailed);
}

function CallParametersPageMethod()
{
   PageMethods.MyFirstParameterPageMethod(
"This is a Demo",onSucceeded,onFailed);
}

function onSucceeded(result,userContext,methodName)
{
  $get(
'div1').innerHTML=result;
}

function onFailed(error,userContext,methodName)
{
  alert(
"An error occurred")
}

</script>

The CallPageMethod method calls the parameterless function MyFirstPageMethod from codebehind and the CallParametersPageMethod calls the code behind function MyFirstParameterPageMethod and passes a string as parameter  

We call the codebehind method as PageMethods.MethodName();

The OnSucceeded parameter indicates the javascript function to be called when the call has succeeded and the result parameter has the result stored in it in our case the string returned from the code behind file.

The OnFailed parameter indicates the javascript function to be called when  error occurs.

In case the code behind function has no parameters then we pass the onSucceeded and OnFailed parameters only.

To pass a parameter to code behind we pass them in the same order as the code behind function and at the end we add the onsucceeded and onfailed parameters as in the CallParametersPageMethod javascript function.

The return value is displayed in the div.

I have attached the complete code of this.

Hope this is helpful to you all.

 

30 Comments

  • It's a pitty, but this one don't work with Master page at all. When Microsoft would be doing fully operational solution?

  • Hi,
    What is the issues with the master page. i got this working with master page as well. i am attaching the demo of the same. Let me know if you still face any issue

    Cheers
    Sohail

  • Interesting. Im getting a js error "PageMethods" is undefined. That said, it's been a very long day so I will have another go tomorrow.

  • No, the point is that if the JavaScript is in the master page it won't work...

  • "Interesting. Im getting a js error "PageMethods" is undefined."

    Make sure your method is Public.

  • It worked fine for me even with master pages!

  • i tried to place the script and server side web method in the master page. and it is showing pagemethod is undefined.
    it is working fine if we place javascript and serverside web method in the inherited page.

  • Had a similar problem with the "PageMethods undefined" error. Was able to solve it by adding the EnablePageMethods="true" attribute to the asp:ScriptManager tag.
    e.g.:

  • Its not working for me - Microsoft JScript runtime error: 'PageMethods' is undefined ..... tried EVRYTHNG

  • its not working same Pagemethods undefined

  • I've managed to get PageMethods working. I got the JScript error that calibur mentioned. Just follow these steps.

    1. Ensure that the EnablePageMethods attribute is set to true on the ScriptManager
    2. Make sure your methods are in the base page (not Master) of your site. (The first contentplaceholder of your page) OR for this example's sake, in Default.aspx.cs
    3. Make sure your methods are public and static.
    4. Decorate the methods with both [WebMethod] and [ScriptMethod] attributes. This gets rid of the blasted Jscript error...
    5. Run your app.

    If your methods raises any exceptions it won't be bubbled up. If you suspect that nothing is happening put a breakpoint on the first line of your method.

  • Did anybody get "Authentication failed" message?? the aspx.cs file and ABMain are in the same project, Does it require authentication??

  • What if you store your page methods in codebehind of a user control that is dynamically loaded in Default.aspx, and JScript methods are in a separate file? Can this be done? I've tried it myself, but I always get: Microsoft JScript runtime error: 'PageMethods' is undefined

  • Hi Anamii,
    i followed all your steps but still i am getting the runtime error Pagemethods.somefunction() not defined.
    Control never reaches to the breakpoint set on the function.

  • I have tried all steps but I still get an "undefinded" value returned. Any other ideas?

  • Just define a button that points to a code behind click even, then get a javascript reference to it via the DOM, the execute its click even. Simple.

  • What if I want to call the codebehind method to populate a test in a label control

    Simething like...

    <asp:Label ID="lblText" runat="server" Text=

    Its not working for me and i dont know the reason..

  • I have C# function and JS both in webusercontrol, can it work?

    Im getting a js error "PageMethods" is undefined

  • I keep getting:
    PageMethods is not defined

    I have the masterpage using the ScriptManager and I have set the EnablePageMethods=true

  • I managed to call functions, HOWEVER, I need the function to get values back to the codebehind, and to put these values in to a class and add the class to a list.
    Thing is, this can't be done in a static function

  • Worked with master pages, no problem. Thank you.

  • Thanks !!! very helpfull

  • It is working for static methods only. how about non-static methods calling from javascript?
    Any way useful stuff.
    Thanks..

  • I made the usercontrol with this method.I put the webmethod in
    ascx.cs file and javascript that call that method in ascx file but it not working..

  • Thanks for this, but are you sure its "static" and not "shared". Cos I get a message saying methods cannot be declared static.

  • To fix the "PageMethods" is undefined error, make sure the method you are calling from the code behind is placed in an 'aspx' file and not an 'ascx' (user control) file!

  • thanks for your sharing

  • I met the same problem when PageMethod is called from user control. Solution is:
    • Place PageMethod on page that contains custom control,
    • Modify Page_Load procedure on this page, add line:
    ScriptManager.GetCurrent(this.Page).EnablePageMethods = true;
    :

  • THis sample application not working for me,,can u plz guide which situations i need to avoid to run this sample successfully...plz help its urgent for me..i m not getting proper out..its giving error of 'undefind'

  • Its awesome.. It works for me.. Thanks a lot..

Comments have been disabled for this content.