Paging a webgrid by Model and Count
I've been developing an asp.net mvc 3 application and I'm using webgrid to sho开发者_高级运维w tabular data in my view. My question is, how can I page some data by counting how many records I have in the database and show the pager of webgrid in my grid's footer? For example, in my repository I have:
public PagedList<Acesso> ObterAcessos(long idPessoa, int pageIndex, int pageSize)
{
return new PagedList<Acesso>
{
PageIndex = pageIndex,
PageSize = pageSize,
Total = Session.QueryOver<Acesso>().Where(acesso => acesso.Pessoa.Id == idPessoa).FutureRowCount(),
List = Session.QueryOver<Acesso>()
.Where(acesso => acesso.Pessoa.Id == idPessoa)
.OrderBy(acesso => acesso.DataInicio).Desc
.Take(pageSize).Skip((pageIndex - 1)*pageSize)
.Future<Acesso>()
};
}
My controller:
public ActionResult Acessos(int page = 1)
{
// 30 records per page
return View(_rep.ObterAcessos(SecurityHelper.User.Id, page, 30));
}
My View:
@model PagedList<Acesso>
@{
ViewBag.Title = "Acessos";
var grid = new WebGrid(rowsPerPage: Model.PageSize, canSort: false, ajaxUpdateContainerId: "grid");
// set the rowCount by Total property and the List property
grid.Bind(rowCount: Model.Total, source: Model.List);
}
<h2>Acessos</h2>
@grid.GetHtml(htmlAttributes: new { id="grid", style="width:700px;" },
mode: WebGridPagerModes.All,
tableStyle: "grid", rowStyle: "gridrow", alternatingRowStyle: "gridrow_alternate",
columns: grid.Columns(
grid.Column("DataInicio", "Data de Inicio", item => item.DataInicio.ToString("dd/MM/yyyy HH:mm")),
grid.Column("IP", "IP"))
)
The data comes right, the counting and the list is right, but when I run this code, it doesn't page data, it shows only the first page and the pager of webgrid isn't shown in my view. Is there any property I can set?
Since you are doing the paging in your model, you should add:
autoSortAndPage: false
to your grid.Bind() so it reads:
grid.Bind(rowCount: Model.Total, source: Model.List, autoSortAndPage: false);
That should enable the paging in the footer the way you want it.
精彩评论