【问题标题】:ASP .NET Core Razor: Model bound complex types must not be abstract or value types and must have a parameterless constructorASP .NET Core Razor:模型绑定的复杂类型不能是抽象类型或值类型,并且必须具有无参数构造函数
【发布时间】:2019-09-19 10:52:39
【问题描述】:

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

    [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);

但我得到了同样的错误。

【问题讨论】:

标签: ajax asp.net-core razor


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果创建了一个新的 Razor Pages 项目并且以下修改使其正常工作:

    产品.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

    【讨论】:

    • 感谢您查看我的问题。只有当我有一个绑定属性 IPagedList 时,POST 才会发生这种情况。我有其他页面和其他模型可以正常工作。
    • 很确定 [BindProperty] 应该只包含在您要发布的值中,因此您可能只想删除它。您能否提供更多包含 POST 方法的代码?
    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 2019-09-17
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多