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

gruber picture gruber · Apr 12, 2011 · Viewed 77.2k times · Source

Is it possible to place a WebMethod in an ascx.cs file (for a UserControl) and then call it from client-side jQuery code?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.

Example: In ArticleList.ascx.cs I have the following code:

[WebMethod]
public static string HelloWorld()
{
    return "helloWorld";
}

In ArticleList.ascx file there I have the call to the WebMethod as follows:

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
            {
                var msg;
                if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "ArticleList.ascx/HelloWorld",
            success: function(msg) {
                alert(msg);
            }
        });

and the error from firebug is:

<html>
<head>
    <title>This type of page is not served.</title>

How can I sucessfully call the server-side WebMethod from my client-side jQuery code?

Answer

Homam picture Homam · Apr 12, 2011

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
}