【问题标题】:Invalid JSON primitive: columnName. jQuery Ajax to WebMethod无效的 JSON 原语:columnName。 jQuery Ajax 到 WebMethod
【发布时间】:2014-02-01 16:19:22
【问题描述】:

我正在使用 jQuery Ajax 通过以下代码传递给 ASP.NET WebMethod:

$.ajax({
   type: 'POST',
   url: 'Page.aspx/generateReport',
   data: {columnList:columnList, gridArrayList: JSON.stringify(gridArrayList) },
   contentType: 'application/json; charset=utf-8',
   dataType: 'json',
   async: true,
   cache: false,
 });

columnList 是单个字符串变量,gridArrayList 是像

这样的对象数组
var gridArrayList = [{id:1,value:"val1"},{id:2,value:"value2"},{id:3,value:"value3"}]

网络方法

public static void generateReport(string columnList, List<dataReportEpad> gridArray) 

我收到以下错误:

ExceptionType
"System.ArgumentException"

消息 “无效的 JSON 原语:columnList。”

堆栈跟踪 " 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 深度) 在 System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入, Int32 depthLimit, JavaScriptSerializer 序列化器)

谁能帮帮我?

【问题讨论】:

    标签: asp.net json jquery webmethod


    【解决方案1】:

    您发送的不是 json,它是 url 编码的表单数据,要发送 json,您必须将 json 字符串作为数据传递。

    data: JSON.stringify({columnList:columnList, gridArray: gridArrayList }),
    

    【讨论】:

    • 我测试了这个建议,但我收到以下错误:ExceptionType "System.InvalidOperationException" 消息“无效的 Web 服务调用,缺少参数值:'gridArray'。” StackTrace" 在 System.Web.Script.Services.WebServiceMethodData.CallMethod(对象目标,IDictionary2 parameters) at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary2 参数)
    • @omixam 你有gridArrayList: gridArrayListgridArray: gridArrayList
    • 我有 gridArrayList: gridArrayList...这是一个对象数组,而 columnList 是一个字符串...
    • @omixam 尝试使用gridArray: gridArrayList,因为`gridArray`是generateReport中的参数名称。
    • 我已经更正了......但还不行......上面的同样错误......我相信我可以同时传递一个字符串和对象数组......但我不能....
    【解决方案2】:

    也许你可以试试这样的:

    Javascript:

    var obj = { 'columnList': columnList, 'gridArrayList': gridArrayList };
    //where columnList is a string and gridArrayList is an array of objects
    
    $.ajax({
       type: 'POST',
       url: 'Page.aspx/generateReport',
       data: JSON.stringify(obj),
       contentType: 'application/json; charset=utf-8',
       dataType: 'json',
       async: true,
       cache: false,
     });
    

    代码背后:

    [WebMethod()]
    public static string generateReport(string columnList, ArrayList gridArrayList) {
    

    【讨论】:

    • 你能在调用 jQuery AJAX 之前 console.log(columnList); 验证它确实包含合法字符串吗?
    • 是...在jQuery Ajax之前我得到...包含columnList的字符串...... ITEM,ID,QTY,Description,Availability...
    猜你喜欢
    • 2016-04-19
    • 2013-02-23
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-18
    相关资源
    最近更新 更多