使用KendoGrid POST有效负载时,JSON编码不正确

时间:2014-08-04 15:48:53

标签: ajax asp.net-mvc json encoding kendo-grid

我绑定到JSON数据源,然后在用户根据页面上的过滤器启动搜索后重新绑定。 JSON有效负载编码不正确,到目前为止我所尝试的任何内容似乎都无法解释原因。

如果我可以将正确的JSON添加到HTTP帖子中,一切都会正常工作,并且首先列出$ .ajax方法。

使用$ .ajax调用(有效)

 $.ajax(
                   {
                       url: '/api/DataProcessing',
                       type: "Post",
                       contentType: "application/json; charset=utf-8",
                       data: '' + JSON.stringify(searchObject),
                       dataType: 'json',
                       success: function (result) {
                           $(".kendoDataProcessing").data("kendoGrid").dataSource = new kendo.data.DataSource({ data: result });
                           $(".kendoDataProcessing").data("kendoGrid").dataSource.read();
                           $(".kendoDataProcessing").data("kendoGrid").refresh();

                       },
                       error: function (xhr, ajaxOptions, thrownError) {
                           alert('Status: ' + xhr.status + ', Error Thrown: ' + thrownError);
                       }
                   });

但是,当我更新kendogrid数据源时,我希望发送一个等效的有效负载,它以一种意想不到的方式对JSON进行编码(请参阅下面的Fiddler中捕获的HTTP请求之前和之后的代码块。编码不正确)

   $(".kendoDataProcessing").kendoGrid({
                        dataSource: {
                            transport: {
                                read: {
                                    url: '/api/DataProcessing',
                                    type: 'Post',
                                    contentType: 'application/json; charset=utf-8',
                                    data: '' + JSON.stringify(searchObject),
                                    dataType: 'json',
                                }
                            },
                            pageSize: 25
                        },

                        height: 620,
                        sortable: true,
                        pageable: true,
                        filterable: true,
                        columns: [
                            {
                                field: "Client",
                                title: "Client Name",
                                width: 120
                            }, {
                                field: "Study",
                                title: "Study",
                                width: 100
                            }, {
                                field: "DataLogId",
                                title: "Batch Description",
                                width: 120
                            }, {
                                field: "Indicator",
                                title: "Indicator",
                                width: 100
                            }, {
                                field: "UserName",
                                title: "Username",
                                width: 110
                            }, {
                                field: "AssessmentPoint",
                                title: "Assessment Point",
                                width: 130
                            }, {
                                field: "DateStamp",
                                title: "Date Stamp",
                                width: 180
                            }]
                    });

**预期的JSON编码(使用$ .ajax方法创建的HTTP调用)**

{"Client":"Choose a client...","Study":"Choose a study...","UserName":"Choose a user...","from":"","To":"","AssessmentPoint":"Choose an AP...","Indicator":"Choose an indicator...","DataLogId":""}

**实际JSON编码(使用Kendogrid数据源更新和重新绑定创建的HTTP调用**

0=%7B&1=%22&2=C&3=l&4=i&5=e&6=n&7=t&8=%22&9=%3A&10=%22&11=C&12=h&13=o&14=o&15=s&16=e&17=+&18=a&19=+&20=c&21=l&22=i&23=e&24=n&25=t&26=.&27=.&28=.&29=%22&30=%2C&31=%22&32=S&33=t&34=u&35=d&36=y&37=%22&38=%3A&39=%22&40=C&41=h&42=o&43=o&44=s&45=e&46=+&47=a&48=+&49=s&50=t&51=u&52=d&53=y&54=.&55=.&56=.&57=%22&58=%2C&59=%22&60=U&61=s&62=e&63=r&64=N&65=a&66=m&67 ... (continues)

看起来它正在将json字符串变成一个排序数组。所以我尝试了一个“floof”的测试字符串,编码为“0 = f& 1 = l& 2 = o& 3 = o& 4 = f”

调用控制器方法:

  public HttpResponseMessage Post([FromBody]DataProcessingSearch dataProcessingSearch)
  {
      // dataProcessingSearch var is null (was passed oddly encoded)     
  }

其他详细信息(搜索对象)

 var searchObject = new Object();
                    searchObject.Client = $('#ClientList').val();
                    searchObject.Study = $('#StudyList').val();
                    searchObject.Site = $('#SiteList').val();
                    searchObject.UserName = $('#UserList').val();
                    searchObject.from = $('#beginSearch').val();
                    searchObject.To = $('#endSearch').val();
                    searchObject.AssessmentPoint = $('#AssessmentPointList').val();
                    searchObject.Indicator = $('#IndicatorList').val();
                    searchObject.DataLogId = $('#DataLogIdText').val();

3 个答案:

答案 0 :(得分:4)

可能是错误的看法: -

1.Json()方法接受C#对象并将它们序列化为JSON     字符串。在我们的例子中,我们想要返回一个JSON对象数组;至     你要做的就是将对象列表传递给Json()。

public JsonResult GetBooks()  
{
    return Json(_dataContext.Books);
}

你能说出上述方法有什么问题吗?如果您还不知道,上述方法将在运行时使用"循环引用"异常。

注意:尝试返回Json,HttpResponse可能会以一种Kendo Grid无法接受的方式序列化数据。这在我的项目中发生在我身上。

尝试此方法: - 现在让我们在JsonResult操作方法中创建它们的实例。

public JsonResult GetFooBar()  
{
    var foo = new Foo();
    foo.Message = "I am Foo";
    foo.Bar = new Bar();
    foo.Bar.Message = "I am Bar";
    return Json(foo);
}

此操作方法将返回以下JSON:

{
    "Message" : "I am Foo",
    "Bar" : {
        "Message" : "I am Bar"
    }
}

在这个例子中,我们得到了我们期望的结果。在序列化foo时,它也进入了Bar属性并序列化了该对象。但是,让我们混合一下并向Bar添加一个新属性。

答案 1 :(得分:4)

  

演示: http://so.devilmaycode.it/json-encoded-improperly-when-using-kendogrid-post-payload

function searchObject(){ 
    return { 
        Client : $('#ClientList').val(),
        Study : $('#StudyList').val(),
        Site : $('#SiteList').val(),
        UserName : $('#UserList').val(),
        from : $('#beginSearch').val(),
        To : $('#endSearch').val(),
        AssessmentPoint : $('#AssessmentPointList').val(),
        Indicator : $('#IndicatorList').val(),
        DataLogId : $('#DataLogIdText').val()
    }
}

// i have putted the dataSource outside just for best show the piece of code...
var dataSource = new kendo.data.DataSource({
    transport: {
        read : {
            // optional you can pass via url 
            // the custom parameters using var query = $.param(searchObject())
            // converting object or array into query sring
            // url: "/api/DataProcessing" + "?" + query,
            url: "/api/DataProcessing",
            dataType: "json",
            // no need to use stringify here... kendo will take care of it.
            // also there is a built-in function kendo.stringify() to use where needed.
            data: searchObject
        },
        //optional if you want to modify something before send custom data...
        /*parameterMap: function (data, action) {
            if(action === "read") {
                // do something with the data example add another parameter
                // return $.extend({ foo : bar }, data);
                return data;
            }
        }*/
    }
});

$(".kendoDataProcessing").kendoGrid({
    dataSource: dataSource, 
    ...
});

评论只是为了更好的解释,你可以完全删除它,如果不需要它。无论如何,代码完全正常工作。

  

答案 2 :(得分:2)

我记得过去使用剑道网格。当时的解决方案是返回jsonp。 (需要跨域工作,不确定它是否适用于你的情况)

建议通过使用JsonpFilterAttribute修改方法来更改控制器方法以返回sjonp。像这样:

[JsonpFilter]
public JsonResult DoTheThing(string data, string moreData)
{
  return new JsonResult
  {
     Data = FetchSomeData(data, moreData)
  };
}

然后在de Kendo网格中尝试使用http://demos.telerik.com/kendo-ui/datasource/remote-data-binding

对于Jsonpfilter属性,请先查看herehere