ASP.NET 4.0 - 使用Jquery,如何调用代码隐藏函数并将数据返回给客户端?

时间:2010-11-05 23:44:18

标签: asp.net jquery ajax

当我点击以下div时:

 <div id="Result">Click here for the time.</div>

我需要运行以下代码隐藏功能:

 <WebMethod()> _
 Public Shared Function GetDate() As String
     Return DateTime.Now.ToString()
 End Function

我需要这个用getDate()函数返回的字符串填充div的内部。我认为这应该使用类似的代码:

<script type="text/javascript">
    $(document).ready(function () {
        // Add the page method call as an onclick handler for the div.
        $("#Result").click(function () {
            $.ajax({
                type: "POST",
                url: "test.aspx/GetDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // Replace the div's content with the page method's return.
                    $("#Result").text(msg.d);
                }
            });
        });
    });
</script>

我已从此网站提取此示例:http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/

然而,我根本无法让它发挥作用。什么都没发生。这只是一个常规的asp.net web项目。除了在我的标记中包含脚本标记以引用jquery之外,我还没有做过任何类型的支持Ajax的业务。

当我点击div时,这就是firebug控制台告诉我的内容:

 POST http://admin/Default.aspx   GetDate   404 Not Found   -18ms

编辑:注意:test.aspx / GetDate必须与您的aspx页面名称和函数名称匹配!

1 个答案:

答案 0 :(得分:3)

<WebMethod()> _
Public Shared Function GetDate() As String
    Return DateTime.Now.ToString()
End Function

必须是“共享”(C#中的“静态”)