【问题标题】:JSON encoded improperly when using KendoGrid POST payload使用 KendoGrid POST 有效负载时 JSON 编码不正确
【发布时间】:2014-09-27 03:50:26
【问题描述】:

我正在绑定到 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();

【问题讨论】:

  • 查看我的回复,我还提供了一个工作演示,您可以查看源代码..希望对您有所帮助。 PS:我没有使用 ASP 但这个问题与服务器端无关。

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


【解决方案1】:

演示: 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, 
    ...
});

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

【讨论】:

  • 成功了!当 Kendo 已经为我执行此操作时,我正在对搜索对象进行字符串化。明确地这样做会使过程加倍并产生不好的结果。干杯!
  • 非常好的信息。拯救了这一天!
【解决方案2】:

什么可能是错误的看法:-

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 添加一个新属性。

【讨论】:

    【解决方案3】:

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

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

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

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

    对于 Jsonpfilter 属性,首先查看 herehere

    【讨论】:

      猜你喜欢
      • 2014-08-16
      • 1970-01-01
      • 2017-06-14
      • 1970-01-01
      • 2015-07-05
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      相关资源
      最近更新 更多