Tuesday, April 13, 2010

'PageMethods' is undefined

“Microsoft JScript runtime error: 'PageMethods' is undefined”

I needed to call a server side method from my ASP.Net AJAX page.

The easy way to do this is to set the EnablePageMethods="true" on the ScriptManager object and then to add a static public method in the code behind file with the attribute: “[System.Web.Services.WebMethod]”

Once I had my simple method working, I tried to refactor my code by moving all the items into a user control…. and suddenly everything stopped working!. The error I was getting is the “PageMethods is undefined”.

All posts pointed to check if the EnablePageMethods was defined on the ScriptManager and that the “[System.Web.Services.WebMethod]” attribute was defined on the method. And they were. The code was all working fine when it was in a single aspx page. My problems started only when I moved the code into a separate ascx user control.

Turns out the problem was that PageMethods was unable to find the public static method that was being called from javascript. The simple fix was for the static method to be moved to the host page’s code-behind file. Once I did that, the issue went away.

Note: the javascript can sit in the user-control. It is only the WebMethod that needs to be moved to the host page.

Now the problem obviously becomes – how do you reuse the user control when the host page is where the code needs to reside? I am not sure there is any way around this dependency. (though, if you hate it – then maybe converting the method to a webservice is a work around. In my case, all I needed was this one method and that was all). Still looking into this usercontrol issue with WebMethods and will update this post if I find out anything else.

No comments: