MVCGrid.net - Grid doesn't page results, shows all records and pager also

609 Views Asked by At

The grid is being displayed which has pager enabled but displays all records without paging. Also the pager is displayed. Code for RegisterGrid() method is as below:-

public static void RegisterGrids()
        {
            GridDefaults defaultSet1 = new GridDefaults()
            {
                Paging = true,
                ItemsPerPage = 5,
                NoResultsMessage = "Sorry, no results were found"
            };

            MVCGridDefinitionTable.Add("grdFiles", new MVCGridBuilder<FilesModel>(defaultSet1)
            .WithAuthorizationType(AuthorizationType.AllowAnonymous)
            .AddColumns(cols =>
            {
                cols.Add("FileName")
                    .WithValueExpression(p => p.Name.ToString());
                cols.Add("LastModified").WithHeaderText("LastModified")
                    .WithValueExpression(p => p.LastModified.ToString());
                cols.Add("Size").WithHeaderText("Size")
                    .WithValueExpression(p => p.Size.ToString());
            })
            .WithRetrieveDataMethod((context) =>
            {
                var res = DisplayFiles();
                return new QueryResult<FilesModel>()
                {
                    Items = res,
                    TotalRecords = res.Count // if paging is enabled, return the total number of records of all pages
                };
            })
            );
        }

View Code is:

@model IEnumerable<FileViewerWeb.Models.FilesModel>

@using MVCGrid.Web;

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="well well-lg" style="padding-top:10px">
    <h2>Explore Uploaded Files</h2>
</div>

@Html.MVCGrid("grdFiles")

Controller Code :-

public ActionResult Index()
{
return View();
}
2

There are 2 best solutions below

0
On

When you are using skip you have firstly to use orderby.

if (options.GetLimitOffset().HasValue)
{
    var limitOffset = options.GetLimitOffset().Value;
    var limitRowCount = options.GetLimitRowcount().Value;
    query = query.OrderBy(c=>c.name) //or add any column you prefer to order the list
        .Skip(limitOffset)
        .Take(limitRowCount);
}
1
On

Change your way of generating the list to a query and then at the end pass the query via a ToList()

var result = new QueryResult<FilesModel>();
var query = db.FilesModel.AsQueryable();

You are missing the code

if (options.GetLimitOffset().HasValue)
{
    var limitOffset = options.GetLimitOffset().Value;
    var limitRowCount = options.GetLimitRowcount().Value;
    query = query
        .Skip(limitOffset)
        .Take(limitRowCount);
}

Finally, at the point of returning use

result.Items = query.ToList();
result.TotalRecords = result.Items.Count();
return result;