who-aditya-nawandar
who-aditya-nawandar

Reputation: 1242

Using paging with WebGrid in MVC4

This is the code in my view. The WebGrid Sort and Filter is working fine. I am trying to implement paging which is not happening.

View:

    @{        
    var grid = new WebGrid(null,
            defaultSort: "",
            rowsPerPage: 10,
            selectionFieldName:"SearchString",
            ajaxUpdateContainerId:"agrid",
            sortFieldName:"SortColumn",
            sortDirectionFieldName:"SortOrder");
    grid.Bind(Model, autoSortAndPage: true, rowCount:20);
}

<div id="agrid">
@grid.GetHtml(
    tableStyle: "webGrid",
    headerStyle: "header",
    alternatingRowStyle: "alt",
    columns: grid.Columns(
        grid.Column("ID"),
        grid.Column("Description")
    )
)
 </div> 

Controller:

        public ActionResult Index(int? page=1, int currentPage = 1, int PageSize = 10, string SortColumn = "", string SortOrder = "", string SearchString = "", int numberOfPages=0, int tr=0)
    {
        DataContextDataContext obj = new DataContextDataContext();
        System.Nullable<int> Total = null;


        var model = obj.TempItemSubClassList(page, PageSize, SortColumn, SortOrder, SearchString, ref Total).ToList();
        tr = (int) Total;

        numberOfPages = (int)(Total + PageSize - 1) / PageSize;

        return View(model);

        //var itemsubclasses = db.ItemSubClasses.Include(i => i.ItemClass);
        //return View(itemsubclasses.ToList());

    }

Upvotes: 1

Views: 15467

Answers (1)

David Clarke
David Clarke

Reputation: 13266

The grid needs to know the total number of rows which in the example you provide has been hard-coded to 20. Add the total number to your model and reference it that way. Also, somewhat counter-intuitively, the autoSortAndPage parameter should be set to false:

@{        
var grid = new WebGrid(null,
        defaultSort: "",
        rowsPerPage: 10,
        selectionFieldName:"SearchString",
        ajaxUpdateContainerId:"agrid",
        sortFieldName:"SortColumn",
        sortDirectionFieldName:"SortOrder");
grid.Bind(Model, autoSortAndPage: true, rowCount:20); <--- total number of rows
}

Upvotes: 3

Related Questions