desperatenoob
desperatenoob

Reputation: 31

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 }))

Upvotes: 3

Views: 4317

Answers (2)

Ahasan
Ahasan

Reputation: 41

**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 }))

Upvotes: 0

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

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

Upvotes: 2

Related Questions