Reputation: 481
Morning all. I've been trying to do this for weeks now but keep going in circles. I have a simple jQuery Ajax function that POSTS Data to a c# function in the code behind.
Basically want to pass a list of selected checkbox fields to be processed. When I submit it, I can see the request being made and the json being sent:
{"item":["Section1","Section2","Section2Sub1","Section2Sub2","Section3"]}
It gets to the server side but when trying to deserialize it, it kicks me back the following error message:
"Invalid JSON primitive: System.Object."
var selection = serializer.Deserialize<string>(item.ToString());
Here's my code snippet:
client side $("#Submit").click(function (e) { var count = 0; var countChecked = 0; areaObj = []; $('input[type=checkbox]').each(function () { count++; if (this.checked) { //countChecked++; //tmp = { // "Area": $(this).attr("id") //}; areaObj.push($(this).attr("id")); } }); }); function subClick(item) { $.ajax({ type: "POST", url: "Default.aspx/SubData", data: JSON.stringify({ item: item }), //data: "{'item':" + JSON.stringify(item) + "}", dataType: "json", contentType: "application/json; charset=utf-8" }); }; c# Default.aspx.cs [WebMethod] public static string SubData(Selection item) { var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //ERROR OCCURS HERE var selection = serializer.Deserialize(item.ToString()); return "this is successful"; } public class Selection { public string Title { get; set; } public string Description { get; set; } public List KeyValues { get; set; } } public class KeyValues { public int AreaID { get; set; } public string Area { get; set; } public int Value { get; set; } }
Can anyone offer any pointers on what is going wrong?
Upvotes: 2
Views: 1450
Reputation: 27367
public static string SubData(Selection item)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//ERROR OCCURS HERE
var selection = serializer.Deserialize(item.ToString());
return "this is successful";
}
Here, item
is not a string (and thus not the JSON being sent). Since you're calling ToString()
on it, it's likely the library is trying to deserialize text similar to System.Object
- which will fail.
At a quick glance at the code, it looks like item
is already deserialized for you, so you don't need to do anything further
Upvotes: 1