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

79,246

Solution 1

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
}

Solution 2

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.

Solution 3

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 some other restrictions so you know which user control should execute the method. Then in your user control you can check for the existance of your restrictions in the querystring, and execute the given method.

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

Solution 4

I came across this issue and used a combination of Dekker, Homan, and Gruber's solutions. All credit goes to them.

I needed to be able to modify the Session when a user clicked a check box. Since the page method has to be static its limited in what you can do inside it and I couldn't modify the Session. So I used jQuery to call a static method in the parent page of the user control that had call a web service method that did the work I needed.

User control's Javascript .ascx file

function chkSelectedChanged(pVal) {
    //called when user clicks a check box
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: '{ "p1":' + pVal+' }',
        url: "ParentPage.aspx/StaticPageMethod",
        success: function (msg) {
            //alert('it worked');
        },
        error: function (msg) {
            alert('boom' + msg);
        }
    });
}

Parent Page Code Behind .aspx.cs file

[WebMethod]
    public static void StaticPageMethod(string pVal)
    {
        var webService = new GridViewService();
        webService.GridCheckChanged(pVal);
    }

Web service .asmx

[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class GridViewService : System.Web.Services.WebService
{
    [WebMethod]
    public void GridCheckChanged(string pVal)
    {
       //Do Work
    }
}

Solution 5

You can do it like that in your Webmethod

Dim uc As UserControl = New UserControl()
Dim objSummarycontrol As SummaryControl = uc.LoadControl("~/Controls/Property/SummaryControl.ascx")
Dim propertyId As String = SessionManager.getPropertyId()
objSummarycontrol.populateTenancyHistory(propertyId)
Share:
79,246
gruber
Author by

gruber

Updated on April 21, 2021

Comments

  • gruber
    gruber about 3 years

    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?

  • gruber
    gruber about 13 years
    For some reasons I cant place this code in asmx or aspx file.
  • Morten Kristensen
    Morten Kristensen over 10 years
    Note that OP is using C# and not VB.
  • Erik Dekker
    Erik Dekker about 10 years
    Why the downvote? Both points work good. If you downvote, then also explain why please..
  • Pankaj Dubey
    Pankaj Dubey over 9 years
    Although the code is in VB but its simple and useful and one can us it in C# without any complication