MVC3 razor Webgrid paging and sorting with more than 2000 records

Millar picture Millar · Jul 30, 2012 · Viewed 16.6k times · Source

I am using a webgrid similar to the one mentioned here

@{
    var grid = new WebGrid(canPage: true, rowsPerPage: ThisController.PageSize, canSort: true, ajaxUpdateContainerId: "grid");
    grid.Bind(Model.Employees, rowCount: Model.TotalRecords, autoSortAndPage: false);
    grid.Pager(WebGridPagerModes.All);
    @grid.GetHtml(htmlAttributes: new { id="grid" },
        columns: grid.Columns(
            grid.Column(format: (item) => Html.ActionLink("Edit", "Edit", new { EmployeeID = item.EmployeeID })),
            grid.Column("FullName"),
            grid.Column("Title")
        ));
}

But in my case I am expecting more than 2000 records ,I want to load only 50 records to be loaded on each page,so that the page will load faster. How can I ensure that only first 50 records are loaded when the page gets loaded.and when my user clicks page2 I want to load the next 50 set of records and so on. Any of you faced anything similar,please suggest me with some sample code

Answer

Leniel Maccaferri picture Leniel Maccaferri · Jul 30, 2012

This MSDN Magazine article shows what you want:

Get the Most out of WebGrid in ASP.NET MVC

Read this section: Adding Paging and Sort

As you can see, the data we’re passing contains the full list of products (295 of them in this example, but it’s not hard to imagine scenarios with even more data being retrieved). As the amount of data returned increases, you place more and more load on your services and databases, while still rendering the same single page of data. But there’s a better approach: server-side paging. In this case, you pull back only the data needed to display the current page (for instance, only five rows).