开发者

How to do paging in the mvc grid?

Any suggestions on how to do 开发者_如何学编程paging in the mvc grid, in an easiest possible way? Please point me to sample code, if any


Ritz,

I think this question has been asked already, but here is the question I'm referring to: Paging & Sorting grids with ASP.Net MVC

Also, this is a very concise tutorial on how to do this:
http://xlib.wordpress.com/2009/06/29/asp-net-mvc-grid-%E2%80%93-part-2-paging/

Some snippets from the above link:

Use this to get a selector on your page to allow the user to determine the number of rows to display per page:

<%= Html.DropDownList("pageSize", CustomerController.PageSizeSelectList(), new { onchange = "onPageSizeChange()" })%> rows per page

Then in a custom page controller write this code:

public static SelectList PageSizeSelectList()
{
    var pageSizes = new List {"1", "2", "5", "10", "100"};
    return new SelectList(pageSizes, "Value");
}

Now add the JavaScript to the page:

//Set hidden variable to go to next/prev/last/first page and submit the form
function goToPage(pageIndex) {
    $("#currentPage").val(pageIndex);
    $("#gridAction").val("CurrentPageChanged");

    submitForm();
}

//Set action performed in hidden variable. When PageSize changes - PageIndex needs to be
//reset to 1. This logic will go on the server side.
function onPageSizeChange(pageIndex) {
    $("#gridAction").val("PageSizeChanged");
    submitForm();
}

function submitForm() {
    var form = $("#grid").parents("form:first");
    form.submit();
}

Then update your page controller to perform the paging:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult List(int currentPage, int pageSize, string gridAction)
{
        //Do logic depending on what action was performed
    if (gridAction == "PageSizeChanged")
        currentPage = 1;

        //Check if there are no results.  In this case return empty list.
    IQueryable query = _customerService.GetQueryable();
    int totalRows = query.Count();
    if (totalRows==0)
        return View(new List());

    int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
    if (totalPages != 1)
    {
        //use LINQ to perform paging
        query = query.Skip((currentPage - 1) * pageSize)
                        .Take(pageSize);
    }

        //Update ViewData collection to display pager stats and pager controls
    UpdatePagerViewData(totalPages, totalRows, currentPage, pageSize);

    List customers = query.ToList();
    return View(customers);
}

I hope this helps,

Thanks!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜