繁体   English   中英

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

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

是否可以将 WebMethod 放在 ascx.cs 文件(用于 UserControl)中,然后从客户端 jQuery 代码调用它?

由于某些原因,我无法将 WebMethod 代码放在 .asmx 或 .aspx 文件中。

示例:在 ArticleList.ascx.cs 中,我有以下代码:

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

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

来自萤火虫的错误是:

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

如何从我的客户端 jQuery 代码成功调用服务器端 WebMethod?

WebMethod 应该是静态的。 所以,你可以把它放在用户控件中,并在页面中添加一个方法来调用它。

编辑:

您不能通过用户控件调用 Web 方法,因为它会在页面内自动呈现。

您在用户控件中拥有的 Web 方法:

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

在 Page 类中添加 web 方法:

[WebMethod]
public static string HelloWorld()
{
    return ArticleList.HelloWorld(); // call the method which 
                                     // exists in the user control
}

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

您不能使用 Jquery Ajax 直接在用户控件中调用方法。

不过,您可以尝试以下方法之一:

  • 将 URL 设置为PageName.aspx?Method=YourMethod或者添加一些其他限制,以便您知道哪个用户控件应该执行该方法。 然后在您的用户控件中,您可以检查查询字符串中是否存在限制,并执行给定的方法。

  • 如果您需要异步执行某些操作,则可以仅使用客户端回调来执行某些方法。 在页面的 GetCallbackResult 中,您可以找到引起回调的控件,并将请求及其参数传递给控件。

我遇到了这个问题,并结合使用了 Dekker、Homan 和 Gruber 的解决方案。 所有的功劳都归功于他们。

我需要能够在用户单击复选框时修改会话。 由于页面方法必须是静态的,因此您可以在其中执行的操作受到限制,而且我无法修改 Session。 所以我使用 jQuery 在用户控件的父页面中调用一个静态方法,该方法调用了一个 Web 服务方法来完成我需要的工作。

用户控件的 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);
        }
    });
}

.aspx.cs 文件背后的父页面代码

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

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

你可以在你的 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)

在 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"%>

在 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 调用:

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

});

代码隐藏方法:

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

控制背后的代码:

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

您无法从用户控件访问 WebMethod,但您可以执行您的功能。

  1. 创建一个简单的网页(aspx)。
  2. 在网页(aspx.cs)中编写 webmethod。
  3. 从网页访问方法。

clyde否,因为 ascx 控件不代表可以从客户端计算机访问的真实 URL。 它们纯粹是服务器端,旨在嵌入其他页面。

您可能想要做的只是有一个 asx 页面,该页面提供与您当前在 ascx 文件中相同的 html 片段。 aspx 页面不一定需要提供完整的 html 文档(等),它可以只呈现您感兴趣的用户控件。

我们一直在 ingrid 插件中使用这种技术,它需要表内容的回调 url。

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

代码背后

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

用户控件

<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:从客户端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