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

纵饮孤独 提交于 2019-12-29 04:28:15

问题


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?


回答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
}



回答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.




回答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.




回答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
    }
}



回答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)



回答6:


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.



回答7:


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;
    }
}



回答8:


It work for me, just put an asp:button and write its event OnClick, if you need return a result you must make that event to set your result in an asp:Label or HiddenField for example:

Code behind

protected void btnSave_OnClick(object sender, EventArgs e) {
    lblresult.Text = "Hello world!";
}

UserControl

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
    <asp:Button ID="btnSave" OnClick="btnSave_Click" runat="server" />
    <asp:Label ID="lblresult" runat="server"/> 
</ContentTemplate>
</asp:UpdatePanel>

Javascript: Call from client-side jQuery code

function call_virtual_webmethod()
{
    var id= '<%= btnSave.ClientID %>;
    $('#'+id).click();
}


来源:https://stackoverflow.com/questions/5638184/how-to-call-an-asp-net-webmethod-in-a-usercontrol-ascx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!