Tuesday, 29 November 2016

Pagination in Mvc Grid

View

@(Html.Awe().Grid("CustomQueryingGrid")
.Url(Url.Action("GetItems", "CustomQueryingGrid"))
.Height(450)
.Columns(
new Column { Bind = "Id", Groupable = false, Sortable = false, Width = 70 },
new Column { Bind = "Person" },
new Column { Bind = "Food" }))

Controller

public class CustomQueryingGridController : Controller
{
public ActionResult GetItems(GridParams g)
{ const int PageSize = 10;
var items = Db.Lunches.AsQueryable();
if (g.SortNames != null)
{
IOrderedQueryable orderedItems = null;
// doing this for demo purposes
// one might use something like Dynamic Linq
// or generate a sql string etc.
for (int i = 0; i < g.SortNames.Length; i++)
{
var column = g.SortNames[i];
var direction = g.SortDirections[i];
if (i == 0)
{
if (column == "Person")
orderedItems = direction == "asc"
? items.OrderBy(o => o.Person)
: items.OrderByDescending(o => o.Person);
else if (column == "Food")
orderedItems = direction == "asc"
? items.OrderBy(o => o.Food)
: items.OrderByDescending(o => o.Food);
}
else
{
if (column == "Person")
orderedItems = direction == "asc"
? orderedItems.ThenBy(o => o.Person)
: orderedItems.ThenByDescending(o => o.Person);
else if (column == "Food")
orderedItems = direction == "asc"
? orderedItems.ThenBy(o => o.Food)
: orderedItems.ThenByDescending(o => o.Food);
}
}
items = orderedItems;
}
var count = items.Count();
var totalPages = (int)Math.Ceiling((float)count / PageSize);
var page = items.Skip((g.Page - 1) * PageSize).Take(PageSize);
return Json(new GridModelBuilder(page.AsQueryable(), g)
{
Key = "Id",
Map = o => new { o.Id, o.Person, o.Food },
PageCount = totalPages,
ItemsCount = count
}.Build());
}
}

No comments:

Post a Comment