如果我的模型中有这样的属性:
[BindProperty]
public IPagedList<Product> Products { get; set; }
然后,当我尝试发布时,我会收到此错误:
An unhandled exception occurred while processing the request.
InvalidOperationException: Could not create an instance of type 'X.PagedList.IPagedList`1[Data.Models.Product, Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, set the 'Products' property to a non-null value in the 'Areas.Catalog.Pages.ProductListModel' constructor.
错误说我可以将属性设置为构造函数中的非空值,因此我尝试在构造函数中进行此操作:
Products = new PagedList<Product>(Enumerable.Empty<Product>(), 1, 10);
但是我遇到了相同的错误。
当我删除[bindproperty]时,它起作用。我的印象是我需要在剃须刀页面上绑定财产,但我想不是吗?
如果创建了一个新的剃须页项目,并且以下修正案使其正常工作:
product.cs:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
index.cshtml:
@page
@using X.PagedList;
@using X.PagedList.Mvc.Core;
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
@{
foreach (var item in Model.Products)
{
<div> @item.Name</div>
}
}
@Html.PagedListPager((IPagedList)Model.Products, page => Url.Action("Index", new { page }))
index.cshtml.cs
public class IndexModel : PageModel
{
public IndexModel()
{
Products = new PagedList<Product>(Enumerable.Empty<Product>(), 1, 10);
}
[BindProperty]
public IPagedList<Product> Products { get; set; }
public void OnGet()
{
}
}
因此,我怀疑您的产品类中的问题是否复杂,您尚未提供代码。
要验证这一点,请使用临时简单的产品类(例如在我的示例中(作为测试。
确认后,尝试使用AutoMapper或Linq的选择方法将产品类投射到更简单的类中,并查看是否有帮助:
https://learn.microsoft.com/en-us/dotnet/csharp/programpramming-guide/conecte/conepts/linq/basic-linq-query-query-operations#selecting-projections
http://docs.automapper.org/en/stable/proctions.html