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

标签 c# jquery asp.net webmethod 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);
            }
        });

firebug 的错误是:

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

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

最佳答案

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
}

关于c# - 如何在 UserControl (.ascx) 中调用 ASP.NET WebMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5638184/

相关文章:

asp.net - 获取在 page_init 中触发回发的控制

javascript - 从服务器端调用 Javascript,目标给出的不起作用

c# - Visual Studio 2010 中的 ASP.Net MVC 1.0

c# - 从 .NEt 中的最大化选项卡中删除还原按钮

javascript - 使用 JQuery 或 CSS3 Transitions(或两者)操作内联文本

jquery - Jquery源码中的core.js文件有什么作用?

javascript - 单击后如何设置 iframe 的样式

javascript - Angularjs 将 $scope 分配给预先存在的 MVC 模型数据

c# - 如何使 DataTable 可枚举?

c# - 如何在 Internet Explorer 中将 URL 添加到受信任的区域?