Основа для ASP-сайта для просмотра сущностей
This commit is contained in:
@@ -0,0 +1,106 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.RazorPages;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using NpgsqlTypes;
|
||||
using Pf2eModel;
|
||||
using Pf2eModel.Model.Base;
|
||||
using Pf2eModel.Model.Enum;
|
||||
|
||||
namespace Pf2eWeb.Pages
|
||||
{
|
||||
public class EntityTypeModel : PageModel
|
||||
{
|
||||
private readonly Pf2eDbContext _context;
|
||||
|
||||
public EntityTypeModel(Pf2eDbContext context)
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
[BindProperty(SupportsGet = true)]
|
||||
public int? PageNum { get; set; }
|
||||
|
||||
public IList<Entity> Entity { get; set; } = default!;
|
||||
|
||||
public EntityType CurrentType;
|
||||
|
||||
public int LastPage;
|
||||
|
||||
public int CurrentPage => PageNum ?? 1;
|
||||
|
||||
public const int PerPage = 30;
|
||||
|
||||
public void OnGet(string type)
|
||||
{
|
||||
CurrentType = Enum<EntityType>(type);
|
||||
|
||||
int count = _context.Entities.Count(entity => entity.Type == CurrentType);
|
||||
|
||||
LastPage = (int)Math.Ceiling(count / (double)PerPage);
|
||||
|
||||
Entity = _context
|
||||
.Entities.Where(entity => entity.Type == CurrentType)
|
||||
.Skip((CurrentPage - 1) * PerPage)
|
||||
.Take(PerPage)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Преобразование значения из JSON в перечисление.
|
||||
/// </summary>
|
||||
/// <param name="value">Значение, которое нужно преобразовать</param>
|
||||
/// <returns>Объект типа `T`, если преобразование успешно, иначе выбрасывает исключение</returns>
|
||||
public static T Enum<T>(string value)
|
||||
where T : Enum
|
||||
{
|
||||
foreach (System.Reflection.FieldInfo field in typeof(T).GetFields())
|
||||
{
|
||||
List<string> variants = [field.Name];
|
||||
|
||||
if (
|
||||
Attribute.GetCustomAttribute(field, typeof(PgNameAttribute))
|
||||
is PgNameAttribute pgAttribute
|
||||
)
|
||||
{
|
||||
variants.Add(pgAttribute.PgName);
|
||||
}
|
||||
|
||||
if (variants.Contains(value))
|
||||
{
|
||||
return (T)field.GetValue(null)!;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Exception($"Can't resolve enum value \"{value}\" for type {typeof(T)}");
|
||||
}
|
||||
|
||||
public List<int> Pagination
|
||||
{
|
||||
get
|
||||
{
|
||||
List<int> pages = [1];
|
||||
|
||||
int start = Math.Max(2, CurrentPage - 1);
|
||||
int end = Math.Min(LastPage - 1, CurrentPage + 1);
|
||||
|
||||
if (start > 2)
|
||||
pages.Add(-1);
|
||||
|
||||
for (int i = start; i <= end; i++)
|
||||
pages.Add(i);
|
||||
|
||||
if (end < LastPage - 1)
|
||||
pages.Add(-1);
|
||||
|
||||
if (LastPage > 1)
|
||||
pages.Add(LastPage);
|
||||
|
||||
return pages;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user