Skip to content

Instantly share code, notes, and snippets.

@yzorg
Created February 19, 2020 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzorg/cbbba87a0f74edf74f42c61143bb63b2 to your computer and use it in GitHub Desktop.
Save yzorg/cbbba87a0f74edf74f42c61143bb63b2 to your computer and use it in GitHub Desktop.
ASP.NET Core Razor Page - Paging
<h1>Index</h1>
<form method="get">
<p>
page @Model.PageNumber of @Model.TotalPages,
showing @Math.Min(Model.PageSize, Model.Count) of @Model.Count rows
</p>
<button type="button" class="btn btn-dark"
@Html.DisabledIf(Model.PageNumber <= 1)
onclick="window.location.href = '@Model.PagedUrlWithFilter(Math.Max(1, Model.PageNumber - 1))'">
&lt;&lt; Previous Page
</button>
<button type="button" class="btn btn-dark"
@Html.DisabledIf(Model.PageNumber >= Model.TotalPages)
onclick="window.location.href = '@Model.PagedUrlWithFilter(Math.Min(Model.TotalPages, Model.PageNumber + 1))'">
Next Page &gt;&gt;
</button>
<pre> table from scaffold, then add search boxes per column </pre>
</form>
namespace MyApp.Pages
{
public partial class IndexModel : PageModel
{
[FromQuery(Name = "page")]
public int PageNumber { get; set; } = 1;
public string PagedUrlWithFilter(int page)
{
if (!this.Request.QueryString.HasValue)
{
if (page > 1)
return $"?page={page}";
return "";
}
var pagedParams = new Dictionary<string, string>(this.Request.Query.Count, StringComparer.OrdinalIgnoreCase);
var query = this.Request.Query;
foreach (var p in query)
{
if (p.Value == Microsoft.Extensions.Primitives.StringValues.Empty || (p.Value.Count == 1 && p.Value[0].Length == 0))
{
_logger.LogDebug($"empty {p.Key}, skipping");
}
else if (pagedParams.ContainsKey(p.Key))
{
_logger.LogDebug($"{p} already present, skipping");
}
else if (p.Key == "page")
{
_logger.LogDebug($"*page* found, skipping");
}
else
{
_logger.LogDebug($"{p}");
pagedParams.Add(p.Key, p.Value.ToString());
}
}
if (page > 1)
{
pagedParams.Add("page", page.ToString());
}
return QueryHelpers.AddQueryString("", pagedParams);
}
[BindProperty(SupportsGet = true)]
public int PageSize { get; set; } = 100;
public int Count { get; set; } = -1;
public int TotalPages => Math.Max(1, (int)Math.Floor(this.Count / Math.Max(1.0, this.PageSize)));
[BindProperty(SupportsGet = true)]
public SearchModel Filter { get; set; } = new SearchModel();
public async Task OnGetAsync([FromQuery] string sort) //, [FromQuery] string filter )
{
// TODO: implement Query()
await Query(sort);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment