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

8

42

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?

Nembutal answered 12/4, 2011 at 15:58 Comment(4)
Can we see some code? The web user control acts similar to a master page. Once the page is rendered out to the browser everything works as if it was one page to begin with.Magdaleno
Ah I see what you're doing. When I use Ajax in asp.net I create a webservice file. It has the .asmx extension. If you use that, it's a great place to store all of your ajax methods.Magdaleno
For some reasons I cant place this code in asmx or aspx file.Nembutal
This question seems related, but not quite identical.Uria
A
33

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
}
Agitato answered 12/4, 2011 at 16:4 Comment(1)
For some reasons I cant place this code in asmx or aspx file.Nembutal
G
13

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.

Gametogenesis answered 12/4, 2011 at 16:18 Comment(0)
L
10

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.

Loralorain answered 10/1, 2012 at 12:19 Comment(1)
Why the downvote? Both points work good. If you downvote, then also explain why please..Loralorain
D
3

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
    }
}
Discoloration answered 4/2, 2013 at 21:30 Comment(0)
H
1

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)
Hypophysis answered 13/9, 2013 at 16:9 Comment(2)
Note that OP is using C# and not VB.Hoekstra
Although the code is in VB but its simple and useful and one can us it in C# without any complicationLethalethal
S
0

Control registration at aspx :

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CustomerRequirements.aspx.cs" EnableViewState="true" Inherits="Bosch.RBNA.CustomerRequirementsServerWeb.Pages.CustomerRequirements" %>

<%@ Register TagPrefix="pp" Src="~/Pages/PeoplePicker.ascx" TagName="PeoplePicker"%>

Control usage in aspx :

<div class="form-group">
    <label for="exampleInputPassword1">Contact to get permisson</label>
    <pp:PeoplePicker runat="server" ID="peoplePicker" ClientIDMode="Static"></pp:PeoplePicker>
</div>

jQuery AJAX Call :

$.ajax({
    type: "POST",
    url: CustomerRequirements.aspx/GetPeoplePickerData + "?SearchString=" + searchText + "&SPHostUrl=" + parent.GetSpHostUrl() + "&PrincipalType=" + parent.GetPrincipalType() + (spGroupName? "&SPGroupName=" + spGroupName: ""),
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        parent.QuerySuccess(queryIDToPass, msg.d);
    },
    error: function (response) {
        var r = jQuery.parseJSON(response.responseText);
        alert("Message: " + r.Message);
        alert("StackTrace: " + r.StackTrace);
        alert("ExceptionType: " + r.ExceptionType);
        parent.QueryFailure(queryIDToPass);
    }

});

Code behind method :

[System.Web.Services.WebMethod]
public static string GetPeoplePickerData()
{
    try
    {
        return PeoplePicker.GetPeoplePickerData();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Code behind of Control :

[WebMethod]
public static string GetPeoplePickerData()
{
    try
    {
        //peoplepickerhelper will get the needed values from the querystring, get data from sharepoint, and return a result in Json format
        Uri hostWeb = new Uri("http://ramsqlbi:9999/sites/app");
        var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, HttpContext.Current.Request.LogonUserIdentity);
        return GetPeoplePickerSearchData(clientContext);
    }
    catch (Exception ex)
    {

        throw ex;
    }
}
Stratagem answered 8/10, 2015 at 9:34 Comment(0)
I
0

You can't access WebMethod from user control but you can perform your functionality.

  1. Create one simple webpage(aspx).
  2. Write webmethod in webpage(aspx.cs).
  3. Access method from webpage.
Impostume answered 16/6, 2017 at 12:47 Comment(0)
G
0

clyde No, because ascx controls don't represent a real URL that can be accessed from a client machine. They're purely server-side meant to embed in other pages.

What you might want to do is just have an aspx page that provides the same snippet of html you currently have in your ascx file. An aspx page doesn't necessarily need to provide a full html document ( etc.), it can just render the user control you're interested in.

We use this technique all the time with the ingrid plugin, which requires a callback url for the table contents.

Gownsman answered 20/4, 2021 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.