tags:

views:

40

answers:

1

hello all,

please can anyone help me on doing the paging in the mvc grid in the easiest way possible i m new to mvc,please can anyone suggest some code for paging in the grid

Thanks ritz

A: 

Ritz,

I think this question has been asked already, but here is the question I'm referring to: http://stackoverflow.com/questions/496470/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!

Scott