简体   繁体   English

如何在 UserControl (.ascx) 中调用 ASP.NET WebMethod

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

Is it possible to place a WebMethod in an ascx.cs file (for a UserControl) and then call it from client-side jQuery code?是否可以将 WebMethod 放在 ascx.cs 文件(用于 UserControl)中,然后从客户端 jQuery 代码调用它?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.由于某些原因,我无法将 WebMethod 代码放在 .asmx 或 .aspx 文件中。

Example: In ArticleList.ascx.cs I have the following code:示例:在 ArticleList.ascx.cs 中,我有以下代码:

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

In ArticleList.ascx file there I have the call to the WebMethod as follows:在 ArticleList.ascx 文件中,我调用了 WebMethod,如下所示:

$.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?如何从我的客户端 jQuery 代码成功调用服务器端 WebMethod?

WebMethod should be static. WebMethod 应该是静态的。 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.您不能通过用户控件调用 Web 方法,因为它会在页面内自动呈现。

The web method which you have in the user control:您在用户控件中拥有的 Web 方法:

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

In the Page class add the web method:在 Page 类中添加 web 方法:

[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).您的方法需要在 .aspx 中(或者我认为 .ashx 或 .asmx 也可以)。 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.由于它实际上是对 Web 服务器进行新调用,因此 IIS 必须处理请求,并且 IIS 不会响应对 .ascx 文件的调用。

You cannot call a method directly in a user control using Jquery Ajax.您不能使用 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.将 URL 设置为PageName.aspx?Method=YourMethod或者添加一些其他限制,以便您知道哪个用户控件应该执行该方法。 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.在页面的 GetCallbackResult 中,您可以找到引起回调的控件,并将请求及其参数传递给控件。

I came across this issue and used a combination of Dekker, Homan, and Gruber's solutions.我遇到了这个问题,并结合使用了 Dekker、Homan 和 Gruber 的解决方案。 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.由于页面方法必须是静态的,因此您可以在其中执行的操作受到限制,而且我无法修改 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.所以我使用 jQuery 在用户控件的父页面中调用一个静态方法,该方法调用了一个 Web 服务方法来完成我需要的工作。

User control's Javascript .ascx file用户控件的 Javascript .ascx 文件

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 .aspx.cs 文件背后的父页面代码

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

Web service .asmx网络服务.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
    }
}

You can do it like that in your Webmethod你可以在你的 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)

Control registration at aspx :在 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 :在 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 : jQuery AJAX 调用:

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

You can't access WebMethod from user control but you can perform your functionality.您无法从用户控件访问 WebMethod,但您可以执行您的功能。

  1. Create one simple webpage(aspx).创建一个简单的网页(aspx)。
  2. Write webmethod in webpage(aspx.cs).在网页(aspx.cs)中编写 webmethod。
  3. Access method from webpage.从网页访问方法。

clyde No, because ascx controls don't represent a real URL that can be accessed from a client machine. clyde否,因为 ascx 控件不代表可以从客户端计算机访问的真实 URL。 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.您可能想要做的只是有一个 asx 页面,该页面提供与您当前在 ascx 文件中相同的 html 片段。 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. aspx 页面不一定需要提供完整的 html 文档(等),它可以只呈现您感兴趣的用户控件。

We use this technique all the time with the ingrid plugin, which requires a callback url for the table contents.我们一直在 ingrid 插件中使用这种技术,它需要表内容的回调 url。

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: 它适用于我,只需放一个asp:按钮并编写其事件OnClick,如果你需要返回一个结果,你必须使该事件在asp:Label或HiddenField中设置你的结果,例如:

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 Javascript:从客户端jQuery代码调用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM