How to call an ASP.NET WebMethod in a UserControl (.ascx) How to call an ASP.NET WebMethod in a UserControl (.ascx) asp.net asp.net

How to call an ASP.NET WebMethod in a UserControl (.ascx)


WebMethod should be static. So, You can put it in the user control and add a method in the page to call it.

Edit:

You can not call a web method through a user control because it'll be automatically rendered inside the page.

The web method which you have in the user control:

public static string HelloWorld(){    return "helloWOrld";}

In the Page class add the web method:

[WebMethod]public static string HelloWorld(){    return ArticleList.HelloWorld(); // call the method which                                      // exists in the user control}


Your method needs to be in an .aspx (or I think .ashx or .asmx will work as well). Since it's actually making a new call to the web server, IIS has to handle the request, and IIS will not respond to calls to .ascx files.


You cannot call a method directly in a user control using Jquery Ajax.

You can try one of the following approaches though:

  • Set the URL to PageName.aspx?Method=YourMethod or maybe add someother restrictions so you know which user control should execute themethod. Then in your user control you can check for the existance ofyour restrictions in the querystring, and execute the given method.

  • You can just use client callback to execute some method, if youneed to do something async. in the GetCallbackResult in the page, youcan find the control that caused the callback, and pass the requestwith its arguments to the control.