Custom Paging for ASP.Net MVC Kendo Grid

23,422

Solution 1

It is defined in the kendo site

CONTROLLER CODE

    //Paging and Sorting
    int currentPage = request.Page;
    int pageSize = request.PageSize;
    string sortDirection = "ASC";
    string sortField = "UpdatedDateTime";

    if (request.Sorts != null && request.Sorts.Count > 0)
    {
        sortField = request.Sorts[0].Member;
        sortDirection = request.Sorts[0].SortDirection.ToString();
    }

//Setting the TOTAL
var result = new DataSourceResult()
{
    Data = orders, 
    Total = total // Total number of records
};

return Json(result);

VIEW

      <div class="GridSearch">

                @(Html.Kendo().Grid<MVC.Models.TransactionHistoryModel>()
    .Name("TransactionHistroyGrid")
     .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(25)
        .ServerOperation(true)
        .Read(read => read
            .Action("TransactionHistorySearch_Read", "TransactionHistoryResults")
            .Data("additionalData")
            )
     )
    .Columns(columns =>
    {
        columns.Bound(p => p.UserId).Filterable(false).Width(40).Title("Userid");
        columns.Bound(p => p.Reviewed).Template(@<text></text>).ClientTemplate("<input id='checkbox'  class='chkbx' type='checkbox' />").Filterable(false).Width(30).Title("Reviewed");
        columns.Bound(p => p.CreatedOnEnd).Format("{0:MM/dd/yyyy}").Filterable(false).Width(50).Title("Created On");
        columns.Bound(p => p.UpdatedOnEnd).Format("{0:MM/dd/yyyy}").Filterable(false).Width(50).Title("Updated On");
        columns.Bound(p => p.Comment).Filterable(false).Width(50).Title("Comment");
    })
    .Pageable()
    .Sortable()
    .Scrollable()
    .Filterable()
    .HtmlAttributes(new { style = "height:325px;" })

  )
            </div>

Solution 2

Here is a custom paging solution we have implemented for Kendo ListView. With minor modification it should work for the grid. The solution consists of a custom DataSoure Object and a custom JSonResult class.

The custom data source:

public class MyDataSource
{
    public object AggregateResults { get; set; }
    public object Data { get; set; }
    public object Errors { get; set; }
    public int Total { get; set; }
}

The custom ActionResult:

public class JsonNetResult : ActionResult
{
    public Encoding ContentEncoding { get; set; }
    public string ContentType { get; set; }
    public object Data { get; set; }

    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }

    public JsonNetResult()
    {
        SerializerSettings = new JsonSerializerSettings();
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty(ContentType)
                                   ? ContentType
                                   : "application/json";

        if (ContentEncoding != null)
            response.ContentEncoding = ContentEncoding;

        if (Data != null)
        {
            var writer = new JsonTextWriter(response.Output) { Formatting = Formatting };

            JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
            serializer.Serialize(writer, Data);

            writer.Flush();
        }
    }

A Typical use in an action method would be:

public ActionResult Orders_Read([DataSourceRequest] Object request)
    {
        int count = 0;
        var ds = (DataSourceRequest)request;
        var ListOfItemsToDisplay = GetItemsWithPagingInfo
                                (
                                    MySearchParameters,
                                    ds.PageSize,
                                    ds.Page,
                                    out count
                                );
        return new JsonNetResult
                                {
                                    Formatting = Formatting.Indented,
                                    Data = new MyDataSource
                                                   {
                                                       Data = ListOfItemsToDisplay
                                                       Total = count,
                                                       AggregateResults = null,
                                                       Errors = null
                                                   }
                                    };
    }
Share:
23,422
LCJ
Author by

LCJ

.Net / C#/ SQL Server Developer Some of my posts listed below -- http://stackoverflow.com/questions/3618380/log4net-does-not-write-the-log-file/14682889#14682889 http://stackoverflow.com/questions/11549943/datetime-field-overflow-with-ibm-data-server-client-v9-7fp5/14215249#14215249 http://stackoverflow.com/questions/12420314/one-wcf-service-two-clients-one-client-does-not-work/12425653#12425653 http://stackoverflow.com/questions/18014392/select-sql-server-database-size/25452709#25452709 http://stackoverflow.com/questions/22589245/difference-between-mvc-5-project-and-web-api-project/25036611#25036611 http://stackoverflow.com/questions/4511346/wsdl-whats-the-difference-between-binding-and-porttype/15408410#15408410 http://stackoverflow.com/questions/7530725/unrecognized-attribute-targetframework-note-that-attribute-names-are-case-sen/18351068#18351068 http://stackoverflow.com/questions/9470013/do-not-use-abstract-base-class-in-design-but-in-modeling-analysis http://stackoverflow.com/questions/11578374/entity-framework-4-0-how-to-see-sql-statements-for-savechanges-method http://stackoverflow.com/questions/14486733/how-to-check-whether-postback-caused-by-a-dynamic-link-button

Updated on September 06, 2020

Comments

  • LCJ
    LCJ almost 4 years

    I have a MVC Kendo Grid as follows. It is working fine with default paging.

    Now, I want to do custom paging. In the controller action we need to know the current page index. Also it should set the “total” count for the grid. [The actual data source will have only 2 records at a time even if there are 100 records in the database. So the grid must know the total number of records in database using “total” attribute.]

    The query should return only 2 records from the database at a time.

    How can we do this custom server paging using the MVC wrapper for Kendo Grid?

    @using (Html.BeginForm())
    { 
    
        @(Html.Kendo().Grid<KendoUIMvcSample.Models.Sample>()    
        .Name("ssgrid222")
        .Columns(columns => {
            columns.Bound(p => p.SampleDescription).Filterable(false).Width(100);
            columns.Bound(p => p.SampleCode).Filterable(false).Width(100);
            columns.Bound(p => p.SampleItems).Filterable(false).Width(100);
        })
        .AutoBind(false)
        .Pageable()
        .Sortable()
        .Scrollable()
        .Filterable()
        .HtmlAttributes(new { style = "height:430px;" })
        .DataSource(dataSource => dataSource
            .Ajax()
            .PageSize(2)
            .Read(read => read.Action("Orders_Read", "Sample")
    )
         )
      )
    }
    

    Controller

    public ActionResult Orders_Read([DataSourceRequest]DataSourceRequest request)
            {
    
                int currentPageNumber = request.Page;
                return Json(GetOrders().ToDataSourceResult(request));
            }