大家早上好。几周来我一直在尝试这样做,但一直在兜圈子。我有一个简单的 jQuery Ajax 函数,它在后面的代码中将数据发布到 c# 函数。
基本上是想传递一个待处理的选中复选框字段列表。 当我提交它时,我可以看到正在发出的请求和正在发送的 json:
{"item":["Section1","Section2","Section2Sub1","Section2Sub2","Section3"]}
它到达了服务器端,但是在尝试反序列化它时,它让我返回以下错误消息:
"Invalid JSON primitive: System.Object."
var selection = serializer.Deserialize<string>(item.ToString());
这是我的代码片段:
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; } }
任何人都可以提供有关问题所在的任何指示吗?
最佳答案
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";
}
这里,item
不是字符串(因此也不是发送的 JSON)。由于您正在对其调用 ToString()
,因此库可能会尝试反序列化类似于 System.Object
的文本 - 这将失败。
快速浏览一下代码,看起来 item
已经为您反序列化了,所以您不需要再做任何事情
关于c# - "Invalid JSON primitive: System.Object."的 Jquery Ajax POST 到 C# WebMethod 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34791169/