ASP .NET Core Razor: Model bound complex types mus

2019-08-28 06:04发布

问题:

If I have a property like this in my model:

    [BindProperty]
    public IPagedList<Product> Products { get; set; }

then when I try to post, I get this error:

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.

The error says I can set the property to a non-null value in the constructor, so I try to do this in the constructor:

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

But I get the same error.

回答1:

If a new Razor Pages project is created and the following amends made it works fine:

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()
    {

    }
}

As such I suspect the issue to be with complexity in your Product class which you have not provided the code for.

To verify that, use a temporary simple Product class (like that in my example) as a test.

Once confirmed, try projecting the product class to a simpler class using Automapper or linq's Select method and see if that helps:

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



回答2:

When I remove [BindProperty] it works. I was under the impression I needed that to bind a property on a Razor page, but I guess not?