AJAX – Calling PageMethods defined on a UserControl

I recently worked with one of my customer, asking for help to migrate his application to AJAX.NET. He had some UserControls which had few methods which needs to be called (ScriptMethods).

If you have a [ScriptMethod] defined in your user control, you cannot call that from your .aspx page using PageMethods.functionname(). Only ScriptMethods defined in the same .aspx page can be called.

A simple workaround would be to have another page method inside the page which in-turn would call the ScriptMethod on the UserControl. Remember all the methods should be public static to be used as a PageMethod.

Below is an example:

UserControl's ScriptMethod:

   1: [WebMethod]
   2: [ScriptMethod(UseHttpGet = true)]
   3: public static string MyUserControlPageMethod()
   4: {
   5:     return "Hello from MyUserControlPageMethod";
   6: }

ASPX page:

   1: <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" ScriptMode="Auto">
   2: </asp:ScriptManager>
   3: <uc1:WebUserControl ID="WebUserControl1" runat="server" />
   5: <script type="text/javascript" language="javascript">
   3:      function callbackFunction(result) {
   4:         $get("WebUserControl1_Label1").innerText = result;
   5:      }
   7:      function CallUserControlPageMethod()
   8:      {
   9:         PageMethods.ForwardingToUserControlPageMethod(callbackFunction);           
  10:      }


In ASPX .cs file:

   1: [WebMethod]
   2: [ScriptMethod]
   3: public static string ForwardingToUserControlMethod(string ddlValue)
   4: {
   5:     return WebUserControl.MyUserControlMethod(ddlValue);
   6: }

Hope this helps!

Skip to main content