【问题标题】:ERROR: Unable to cast object of type 'System.Collections.Generic.List' to type 'X.PagedList.IPagedList'错误:无法将“System.Collections.Generic.List”类型的对象转换为“X.PagedList.IPagedList”类型
【发布时间】:2018-03-22 15:07:00
【问题描述】:

我使用 List 而不是 IEnumerable 模型

我的控制器

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

我的观点

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

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

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-5 pagedlist


    【解决方案1】:

    **控制器动作**

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

    查看页面

        @using PagedList
        @using PagedList.Mvc
        @model IEnumerable <Employee>
    
        @Html.Partial("EmployeeList", Model)
    
        @Html.PagedListPager((IPagedList)Model, page => Url.Action("Index", new { page }))
    

    【讨论】:

      【解决方案2】:

      IEnumerable&lt;EmployeeViewModel&gt; 不能直接转换为 IPagedList(IPagedList)Model.AsEnumerable(),因为它们是不同的实例。您应该使用ToPagedList 方法作为View 参数返回PagedList 实例(假设employeesList&lt;EmployeeViewModel&gt; 或视图模型数组):

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

      并像这样使用PagedListPager 内部的绑定模型:

      @model PagedList.IPagedList<EmployeeViewModel>
      @using PagedList.Mvc; 
      
      @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
      

      并在HtmlHelper.Partial 中通过Model 传递IPagedList

      @Html.Partial("EmployeeList", Model)
      

      类似问题:

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

      【讨论】:

      • 感谢修复后显示传递到字典的模型项的类型为“X.PagedList.PagedList”,但此字典需要“System.Collections.Generic.List”类型的模型项
      • 你能在部分视图和视图代码中显示你的@model 指令吗?似乎您仍在将IEnumerable 用于@model 指令,如本期:stackoverflow.com/questions/40373595/…。将其更改为正确使用PagedList
      • 这个? @Html.Partial("EmployeeList", Model) @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
      • 是的,Model.AsEnumerable() 应该只是 Model,因为你想绑定 PagedList(前者将返回 IEnumerable&lt;PagedList&gt;)。
      • 即使我将其更改为模型,它仍然显示错误:传递到字典中的模型项的类型为“X.PagedList.PagedList1[App.Models.EmployeeViewModel]', but this dictionary requires a model item of type 'System.Collections.Generic.List1[App.Models.EmployeeViewModel]”。你需要什么代码来验证我的错误在哪里?感谢您的耐心和帮助
      猜你喜欢
      • 2022-01-14
      • 2016-02-10
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 2015-09-14
      • 1970-01-01
      相关资源
      最近更新 更多