Model binding the sort field from KendoUI Grid

天大地大妈咪最大 提交于 2019-12-05 09:27:08
Atanas Korchev

The ASP.NET MVC model binder does not understand expressions like sort[0][field]. It understands only sort[0].field which is unfortunate because jQuery.ajax submits nested objects in the former format.

There are two ways to solve the problem:

  1. Use Kendo UI Complete for ASP.NET MVC. It comes with a built-in model for the grid request. More info can be found here.
  2. Create a parameterMap and translate the sort expression:

    parameterMap: function(options) {
         var result = {
           pageSize: options.pageSize,
           skip: options.skip
         };
    
         if (options.sort) {
             for (var i = 0; i < options.sort.length; i++) {
                result["sort[" + i + "].field"] = options.sort[i].field;
                result["sort[" + i + "].dir"] = options.sort[i].dir;
             }
         }
    
         return result;
    }
    

UPDATE FROM QUESTION AUTHOR:

I did end up using parameter map, but rather than re-structure the sort field I simply stringified the options and specified the contentType on the CRUD transports. The model binder knows to bind to the stringified JSON as long as the contentType is specified.

transport: {
    read: {
        url: '...',
        type: 'POST',
        contentType: 'application/json'
    },
    update: {
        url: '...',
        type: 'POST',
        contentType: 'application/json'
    },
    destroy: {
        url: '...',
        type: 'POST',
        contentType: 'application/json'
    },
    create: {
        url: '...',
        type: 'POST',
        contentType: 'application/json'
    },
    parameterMap: function (options, type) {
        return JSON.stringify(options);
    }
}
YYL

I found an answer from another thread using IDictionary<string, string>[] sort, which seems to be the most elegant and cleanest way to capture the sort criteria on the server side. I don't use a custom model binder as the sample code showed. I simply capture the sorting criteria using IDictionary array and then apply that criteria to my own data source. Here is the link to that discussion thread: Using IDictionary array to capture Kendo UI sorting criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!