Files
draletaha/DrSousan.Api/Pages/Blog/Index.cshtml.cs
T
soroush.asadi 872e5c1818
CI/CD / CI · dotnet build (push) Successful in 35s
CI/CD / Deploy · drsousan (push) Successful in 28s
fix(blog): repair pagination on public and admin interfaces
Public /blog: the handler param was named `page`, which is a reserved
route token in Razor Pages and never binds — so every page silently
showed the same first 10 posts. Renamed the query param to `pg`
([FromQuery(Name="pg")]) and updated the pagination links to match.

Admin: the posts table had no pagination and dumped all rows at once.
Added client-side pagination (10/page) with a prev/next + numbered bar
over the already-loaded posts array.

Verified: public page1=10/page2=4 with zero overlap; admin shows
‹ 1 2 › with correct row counts and active state per page.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-11 00:23:22 +03:30

63 lines
2.2 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using DrSousan.Api.Data;
using DrSousan.Api.Models;
namespace DrSousan.Api.Pages.Blog;
public class BlogIndexModel : PageModel
{
private readonly AppDbContext _db;
private const int PageSize = 10;
public BlogIndexModel(AppDbContext db) => _db = db;
public List<BlogPost> Posts { get; private set; } = new();
public List<BlogCategory> Categories { get; private set; } = new();
public int CurrentPage { get; private set; } = 1;
public int TotalPages { get; private set; } = 1;
public int TotalPosts { get; private set; } = 0;
public string? ActiveCat { get; private set; }
// NOTE: the query param is "pg", not "page" — "page" is a reserved route token in
// Razor Pages and never binds here, which silently pins every request to page 1.
public async Task<IActionResult> OnGetAsync([FromQuery(Name = "pg")] int pg = 1, string? category = null)
{
CurrentPage = pg < 1 ? 1 : pg;
ActiveCat = category;
var q = _db.BlogPosts.Include(p => p.Category).Where(p => p.IsPublished);
if (!string.IsNullOrEmpty(category))
q = q.Where(p => p.Category != null && p.Category.Slug == category);
TotalPosts = await q.CountAsync();
TotalPages = Math.Max(1, (int)Math.Ceiling(TotalPosts / (double)PageSize));
if (CurrentPage > TotalPages) CurrentPage = TotalPages;
Posts = await q
.OrderByDescending(p => p.PublishedAt)
.Skip((CurrentPage - 1) * PageSize)
.Take(PageSize)
.ToListAsync();
Categories = await _db.BlogCategories
.Include(c => c.Posts)
.ToListAsync();
ViewData["SiteName"] = await GetSiteNameAsync();
ViewData["Title"] = "وبلاگ | دکتر سوسن آل‌طه";
return Page();
}
private async Task<string> GetSiteNameAsync()
{
var s = await _db.SiteSettings
.FirstOrDefaultAsync(x => x.Section == "hero" && x.Key == "name");
return s?.Value ?? "دکتر سوسن آل‌طه";
}
}