1
早上好。我一直试图这样做几个星期,但继续围绕。我有一个简单的jQuery Ajax函数,它将POSTS数据转换为后面代码中的c#函数。Jquery Ajax POST到C#WebMethod错误与“无效的JSON基元:System.Object。”
基本上想传递一个选定的复选框字段列表进行处理。 当我提交它,我可以看到的请求而作出,并正在发送的JSON:
{"item":["Section1","Section2","Section2Sub1","Section2Sub2","Section3"]}
它获取到服务器端,但试图反序列化时,它踢我回来了以下错误消息:
“无效的JSON图元: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; } }
任何人都可以提供对正在发生的事情不对任何指针?
您使用item.ToString()的''指示我说你实际上并没有解析你认为你的json。您正在解析文本'System.Object',它是对象上'.ToString()'的结果。如果你在反序列化行上放置了一个断点,你会发现'item'不是一个字符串。 – Rob
它进一步看起来'item'已经*了反序列化的对象。 – Rob
*拍打额头*当然是。我花了这么长时间看这个,我变得有点雪盲了....感谢Rob!你可以“回答这个问题”,我会将其标记为解决方案 – Nick