【问题标题】:How to call an ASP.NET WebMethod in a UserControl (.ascx)如何在 UserControl (.ascx) 中调用 ASP.NET WebMethod
【发布时间】:2011-08-04 00:52:26
【问题描述】:

是否可以将 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?

【问题讨论】:

  • 我们可以看一些代码吗? Web 用户控件的作用类似于母版页。一旦页面呈现给浏览器,一切就好像它是一个页面一样开始。
  • 啊,我明白你在做什么了。当我在 asp.net 中使用 Ajax 时,我创建了一个 web 服务文件。它具有 .asmx 扩​​展名。如果你使用它,它是存储所有 ajax 方法的好地方。
  • 由于某些原因,我无法将此代码放在 asmx 或 aspx 文件中。
  • This question 似乎相关,但并不完全相同。

标签: c# jquery asp.net webmethod ascx


【解决方案1】:

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

编辑:

您不能通过用户控件调用 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
}

【讨论】:

  • 由于某些原因,我无法将此代码放在 asmx 或 aspx 文件中。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    您可以尝试以下方法之一:

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

    • 你可以只使用客户端回调来执行一些方法,如果你 需要做一些异步的事情。在页面的 GetCallbackResult 中,您 可以找到引起回调的控件,并传递请求 及其对控件的参数。

    【讨论】:

    • 为什么投反对票?这两点都很好。如果您投反对票,请同时解释原因..
    【解决方案4】:

    我遇到了这个问题,并结合使用了 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
        }
    }
    

    【讨论】:

      【解决方案5】:

      您可以在您的 Web 方法中这样做

      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)
      

      【讨论】:

      • 请注意,OP 使用的是 C# 而不是 VB。
      • 虽然代码是用VB编写的,但它简单实用,可以在C#中使用,没有任何复杂性
      【解决方案6】:

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

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

      【讨论】:

        【解决方案7】:

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

        【讨论】:

          【解决方案8】:

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

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

          我们一直使用这种技术和 ingrid 插件,它需要一个回调 url 用于表格内容。

          【讨论】:

            猜你喜欢
            • 2016-08-15
            • 2013-10-07
            • 1970-01-01
            • 2013-10-05
            • 1970-01-01
            • 1970-01-01
            • 2011-10-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多