关于c#:jQuery,JSON和ASP.NET PageMethods

jQuery, JSON and ASP.NET PageMethods

找到一篇关于使用jquery使用codebehind webmethod的好文章。我正在尝试在我的网站上应用它。但我一直得到以下错误,尽管我确保参数名是相同的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        $(".StreamLike").live("mouseover", function () {
            var Id = $(this).parent().parent().find(".StreamIndex").html();
            alert(Id);
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/GetLikes',
                data: {"Id": Id },
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: LikesSuccess,
                error: LikesError
            });
        });

        function LikesSuccess(result, userContext, methodName) {
            for (var i in result) {
                alert(result[i]);
            }

WebMethod:

1
2
3
4
5
6
7
8
9
10
11
[WebMethod]
public static string[] GetLikes(int Id)
{
    List<Like> Likes = Like.GetById(Id, false);
    string[] Senders = new string[Likes.Count];
    for (int i = 0; i < Likes.Count; i++)
    {
        Senders[i] = Likes[i].Sender;            
    }
    return Senders;
}

完整的错误信息如下:

{"Message":"Invalid JSON primitive: Id.","StackTrace":" at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()

at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32
depth)

at
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String
input, Int32 depthLimit, JavaScriptSerializer serializer)

at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer
serializer, String input, Type type, Int32 depthLimit)

at
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String
input)

at
System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext
context, JavaScriptSerializer serializer)

at
System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData
methodData, HttpContext context)

at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.ArgumentException"}

它总是像镜子一样…


试试这个…

数据:json.stringify("id":id)

文章将你的"id"对象转换成名称/值对。例如,ID=12345。你必须先将对象串起来。


您可以使用chrome的开发工具查看响应值