49 lines
1.9 KiB
C#
49 lines
1.9 KiB
C#
|
|
using AsadiTools.Data;
|
||
|
|
using AsadiTools.Models;
|
||
|
|
using AsadiTools.Services;
|
||
|
|
using Microsoft.AspNetCore.Mvc;
|
||
|
|
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||
|
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
|
||
|
|
namespace AsadiTools.Pages.Shop;
|
||
|
|
|
||
|
|
public class ShopIndexModel(AppDbContext db, CartService cart) : PageModel
|
||
|
|
{
|
||
|
|
public const int PageSize = 12;
|
||
|
|
|
||
|
|
public List<Product> Products { get; private set; } = [];
|
||
|
|
public string? Category { get; private set; }
|
||
|
|
public string? Brand { get; private set; }
|
||
|
|
public string? Search { get; private set; }
|
||
|
|
public int CurrentPage { get; private set; } = 1;
|
||
|
|
public int TotalPages { get; private set; }
|
||
|
|
public int TotalCount { get; private set; }
|
||
|
|
|
||
|
|
public async Task OnGetAsync(string? category, string? brand, string? search, int page = 1)
|
||
|
|
{
|
||
|
|
Category = category;
|
||
|
|
Brand = brand;
|
||
|
|
Search = search;
|
||
|
|
|
||
|
|
var q = db.Products.Where(p => p.IsActive);
|
||
|
|
if (category is not null) q = q.Where(p => p.Category == category);
|
||
|
|
if (brand is not null) q = q.Where(p => p.Brand == brand);
|
||
|
|
if (search is not null) q = q.Where(p => p.NameFa.Contains(search) || (p.NameEn != null && p.NameEn.Contains(search)) || (p.Sku != null && p.Sku.Contains(search)));
|
||
|
|
|
||
|
|
TotalCount = await q.CountAsync();
|
||
|
|
TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);
|
||
|
|
CurrentPage = Math.Clamp(page, 1, Math.Max(1, TotalPages));
|
||
|
|
|
||
|
|
Products = await q.OrderByDescending(p => p.Id)
|
||
|
|
.Skip((CurrentPage - 1) * PageSize)
|
||
|
|
.Take(PageSize)
|
||
|
|
.ToListAsync();
|
||
|
|
}
|
||
|
|
|
||
|
|
public IActionResult OnPostAddToCart(int productId, string nameFa, decimal price, string? sku)
|
||
|
|
{
|
||
|
|
cart.AddItem(new CartItem { ProductId = productId, NameFa = nameFa, Price = price, Sku = sku, Qty = 1 });
|
||
|
|
return RedirectToPage();
|
||
|
|
}
|
||
|
|
}
|