Reputation: 2785
Found a great article about using jQuery to consume a codebehind WebMethod. I am trying to apply it on my website. But I keep getting the following error though I ensured that the param names are the same.
$(".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:
[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;
}
The full error message is as follows:
{"Message":"Invalid JSON primitive: Id.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
It's always hitting LikesError...
Upvotes: 0
Views: 3861
Reputation: 856
you can use the develop tool of chrome to see the response value
Upvotes: 0
Reputation: 305
Try this...
data: JSON.stringify({ "Id": Id })
The post is turning your "Id" object into name/value pairs. e.g. Id=12345. You have to stringify the object first.
Upvotes: 9