简体   繁体   中英

ERROR: Unable to cast object of type 'System.Collections.Generic.List' to type 'X.PagedList.IPagedList'

I use List instead of IEnumerable model

My Controller

 public ActionResult Index(int? page)
        { 
            var pageNumber = page ?? 1;
            var itemCount = employees.ToPagedList(pageNumber, 5);
            return View(employees.ToList());
        }

My View

@Html.Partial("EmployeeList", Model.AsEnumerable())

@Html.PagedListPager((IPagedList)Model.AsEnumerable(), page => Url.Action("Index", new { page }))

IEnumerable<EmployeeViewModel> can't be directly cast to IPagedList with (IPagedList)Model.AsEnumerable() since they're different instances. You should return a PagedList instance using ToPagedList method as View argument (assumed employees is an List<EmployeeViewModel> or array of viewmodels):

public ActionResult Index(int? page)
{ 
    var pageNumber = page ?? 1;
    return View(employees.ToPagedList(pageNumber, 5));
}

And use the bound model inside PagedListPager like this:

@model PagedList.IPagedList<EmployeeViewModel>
@using PagedList.Mvc; 

@Html.PagedListPager(Model, page => Url.Action("Index", new { page }))

And pass the IPagedList through Model in HtmlHelper.Partial :

@Html.Partial("EmployeeList", Model)

Similar issue:

How to load first x items and give user the option to load more in MVC.NET

**Controller Action **

    public ActionResult Index(int? page)
        { 
            var pageNumber = page ?? 1;            
            return View(employees.ToList().ToPagedList(pageNumber, 5));
        }


View page

    @using PagedList
    @using PagedList.Mvc
    @model IEnumerable <Employee>

    @Html.Partial("EmployeeList", Model)

    @Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM