This is a migrated thread and some comments may be shown as answers.

serverSorting datasource for webui.grid

1 Answer 204 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Paul
Top achievements
Rank 1
Paul asked on 11 Apr 2014, 08:50 PM
Basically I am implementing a variant of the demonstration shown here for grid with detail template

  http://demos.telerik.com/kendo-ui/web/grid/detailtemplate.html

I almost have it working but.. some filter operations aren't working.

I have it working now such that the grid only requests the data it needs from the controller, which was a problem at first.. Initially I was getting ALL data from the controller and it was filtered on the grid.  Not what I wanted as I anticipate the list of data might grow to be quite large eventually.

During this exercise, I switched from the asp.net grid to the kendui.web grid as it seems the asp.net grid did not have a way to enable serverfiltering in its datasource..?  I am ok with using the kendo.ui web now and then 

I end up with the following for my grid/datasource for the main grid
There is a detail grid that I dont' show for brevity.. it has the same issue in that sorting is not working.
This seems overly verbose but it works (almost).  I took this example from this blog
  http://blog.longle.net/2012/04/13/teleriks-html5-kendo-ui-grid-with-server-side-paging-sorting-filtering-with-mvc3-ef4-dynamic-linq/


$(document).ready(function () {
    $("#ordersGrid").kendoGrid({
        pageable: true,
        sortable: true,
        detailTemplate: kendo.template($("#template").html()),
        detailInit: detailInit,
        dataBound: function () {
            this.expandRow(this.tbody.find("tr.k-master-row").first());
        },
        columns: [
            {
                field: "shopOrderHexID",
                title: "ID",
            },
            {
                field: "characterName",
                title: "Pilot"
            },
            {
                field: "CreatedDate",
                title: "Created",
                format: "{0:yyyy.MM.dd}"
            },
            {
                field: "LastModifiedDate",
                title: "Last Modified",
                format: "{0:yyyy.MM.dd}"
            }],
        dataSource: {
            transport: {
                read: "/ShopOrders/OrderList",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: {}
            },
            parameterMap: function (options) {
                return JSON.stringify(options);
            },
            schema: {
                model: {
                    fields: {
                        shopOrderHexID: { type: "string" },
                        characterName: { type: "string" },
                        characterID: { type: "number" },
                        CreatedDate: { type: "date" },
                        LastModifiedDate: { type: "date" }
                    }
                },
                data: "Data",
                total: "Total"
            },
            pageSize: 5,
            serverPaging: true,
            serverSorting: true,
            serverFiltering: true
        }
    });
});


So here is what works.

serverpaging is definitely working. I can observe the separate calls as I page through the data and I can review the results, I see that it definitely only pulled a single page of information.  Great!

  http://localhost:58507/ShopOrders/OrderList?take=5&skip=0&page=1&pageSize=5
  http://localhost:58507/ShopOrders/OrderList?take=5&skip=5&page=2&pageSize=5

Ok so far so good.
What doesn't work though.. is sorting.
If I select any column to be sorted (ID, or Created) for example, I can see the request sent to the controller but the controller is returning with unsorted data..as if the sort is not support.

These two requests from the grid, return the same exact data for example.. that's not good.
I can see it asking for sort on the shopOrderHexID which is a valid field in the data I pass to ToDataSourceResult... but... it isn't sorted.
Basically I should be getting the last 5 entries in the data table but I still get the same first 5 entries, even sorted in the same order.

  http://localhost:58507/ShopOrders/OrderList?take=5&skip=0&page=1&pageSize=5

 http://localhost:58507/ShopOrders/OrderList?take=5&skip=0&page=1&pageSize=5&sort%5B0%5D%5Bfield%5D=shopOrderHexID&sort%5B0%5D%5Bdir%5D=asc&sort%5B0%5D%5Bcompare%5D=

Now I notice that if I ask for serverSorting: false, then the grid does sort the data when I manipulate the columns, but it is only sorting the data it has at ahnd which is of course only the data on the current page.  Ok fine.. but thats not what I want.  I want sorting by a column to basicaly be showing the first or last 5 items in the table... right?  That is what the end-user is going to expect and desire I think.. 

Ok so the magic is likely in the controller (though it might be in the configuration of the datasource above)
My controller function is


// returns a list of products in a specific category for the active user
public JsonResult OrderList([Kendo.Mvc.UI.DataSourceRequest]Kendo.Mvc.UI.DataSourceRequest request)
{
    var userID = User.Identity.GetUserId();
 
    // build results, make sure to return only orders from current user
    var orders = repository.shopOrders
        .Where(order => order.userID == userID)
        // avoid circular reference by converting to view model, and flatten the model
        .Select(e => new ShopOrderViewModel
        {
            shopOrderID = e.shopOrderID,
            characterName = e.characterName,
            characterID = e.characterID,
            CreatedDate = e.CreatedDate,
            LastModifiedDate = e.LastModifiedDate,
            totalCost = e.orderItems
                .Sum( o => o.quantity * o.price ),
            paymentAmount = ( e.shopOrderPaymentRecords.Count() > 0 )?
                e.shopOrderPaymentRecords.Sum(p => p.payment):0,
            //paid = (paymentAmount >= totalCost)
        })
        // convert to list so I can manipulate the data a little easily
        .ToList();
 
    // populate the hex value of the shopOrderID (linq to objects/sql doesn't like doing this directly)
    for (int i = 0; i < orders.Count(); i++)
    {
        orders.ElementAt(i).shopOrderHexID = orders.ElementAt(i).shopOrderID.ToString("X8");
    }
 
    // apply filter to the results... that's what this does right?
    Kendo.Mvc.UI.DataSourceResult result = orders.ToDataSourceResult(request);
    // return data as json
    return Json(result, JsonRequestBehavior.AllowGet);
}

1 Answer, 1 is accepted

Sort by
0
Atanas Korchev
Telerik team
answered on 15 Apr 2014, 12:07 PM
Hello Paul,

There are a few issues with the data source configuration:

1. The dataType, contentType, type and data options should be nested under transport.read:
OLD:
transport: {
    read: "/ShopOrders/OrderList",
    dataType: "json",
    type: "POST",
    contentType: "application/json; charset=utf-8",
    data: {}
}

NEW:
transport: {
      read:  {
        url: "/ShopOrders/OrderList",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: {}
     }
  }

2. The parameterMap option should be nested under transport:
OLD:
transport: {
  /* snip */
},
parameterMap: function (options) {
    return JSON.stringify(options);
}

NEW:
transport: {
      read:  {
        url: "/ShopOrders/OrderList",
        dataType: "json",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: {}
     },
     parameterMap: function(options) {
          return JSON.stringify(options);
     }
  }

Then in your controller you are using ToDataSourceResult and Kendo.Mvc.UI.DataSourceRequest which only work with the ASP.NET MVC wrappers. If you want to implement server-side paging, sorting and filtering but don't want to use the ASP.NET MVC wrappers we recommend checking this project: https://github.com/telerik/kendo-examples-asp-net-mvc/tree/master/grid-crud. It uses an open source library which will do the paging, sorting and filtering.

Regards,
Atanas Korchev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
Tags
Grid
Asked by
Paul
Top achievements
Rank 1
Answers by
Atanas Korchev
Telerik team
Share this question
or