使用c#和asp.net的Jquery回发返回null

本文关键字:返回 null Jquery asp net 使用 | 更新日期: 2023-09-27 18:16:01

我试图使用jquery调用一个c#函数时,一个按钮被点击。结果是返回变量(msg)为空。

按钮代码:

    <button id="test1" runat="server">Get Text</button>
JQuery代码:
    $(document).ready(function() {
        $("#test1").click(function() {
            $.ajax({
                type: "POST",
                url: "ServiceDirectoryAdd.aspx/GetCurrentDate",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(msg) {
                    alert(msg);
                }
            });

        });
    });
c#函数:
    [WebMethod]
    public static string GetCurrentDate()
    {
        return "foo";
    } 

如我所说,返回变量msg返回null。我做错了什么吗?

编辑:在c#函数中设置断点后,程序似乎没有进入函数。

使用c#和asp.net的Jquery回发返回null

是否添加了脚本管理器到页面?如果你没有加的话。请添加它,然后脚本管理器"EnablePageMethod"属性为true。

这里是链接。http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

尝试索引msg

alert(msg[0]); or  alert(msg.d);

您试过GET吗?

$.get("ServiceDirectoryAdd.aspx/GetCurrentDate", function(data){
    alert(data || data.d);
});

编辑webmethod接收get

[WebMethod]
[ScriptMethod(UseHttpGet=true)]
public static string GetCurrentDate()
{
    return "foo";
}