ASP .NET Core Razor:模型绑定的复杂类型不能为抽象或值类型,并且必须具有无参数构造函数

时间:2019-04-30 18:16:31

标签: ajax asp.net-core razor

如果我的模型中有这样的属性:

    [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.

错误表明我可以在构造函数中将属性设置为非null值,所以我尝试在构造函数中执行此操作:

Products = new PagedList<Product>(Enumerable.Empty<Product>(), 1, 10);

但是我遇到同样的错误。

2 个答案:

答案 0 :(得分:0)

如果创建了一个新的Razor Pages项目,并且进行了以下修改,则它可以正常工作:

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://docs.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()
    {

    }
}

因此,我怀疑问题出在您的Product类中,而您尚未提供代码。

要验证这一点,请使用一个临时的简单Product类(如我的示例中的类)作为测试。

一旦确认,请尝试使用Automapper或linq的Select方法将产品类投影到更简单的类中,看是否有帮助:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/basic-linq-query-operations#selecting-projections

http://docs.automapper.org/en/stable/Projection.html

答案 1 :(得分:0)

当我删除[BindProperty]时,它可以工作。我的印象是我需要在Razor页面上绑定属性,但是我想不是吗?