如何修复“传递到字典中的模型项是类型但此字典需要类型的模型项”

How to Fix " The model item passed into the dictionary is of type but this dictionary requires a model item of type "

我想使用 Pagedlist 在 table 中进行分页,但出现错误

The model item passed into the dictionary is of type 'PagedList.PagedList1[System.Collections.Generic.KeyValuePair2[MyProject.Data.Models.User,System.Collections.Generic.IEnumerable`1[MyProject.Data.Models.Role]]]', but this dictionary requires a model item of type

我可以进行分页,但只能用于一种型号,例如使用代码 "View(db.Roles.ToList().ToPagedList(pageNumber, pageSize))"。但是对于这种情况是不同的,这里我使用了两个模型,即用户和角色。我用字典来调用这两个模型。我对如何使用 PagedList 在视图中实现它感到困惑。这是我的代码 tried.Thanks

public ActionResult Index(int? page)
{
    int pageSize = 2;
    int pageNumber = (page ?? 1);
    Dictionary<User, IEnumerable<Role>> userRoles = userRoleRepo.GetDictionary_UserAndRolesOfEachUser();
   return View(userRoles.ToPagedList(pageNumber, pageSize));
}

查看

 @model PagedList.IPagedList<Dictionary<MyProject.Data.Models.User, IEnumerable<MyProject.Data.Models.Role>>>
 <table class="table">
    <tr class="header">
        <th> UserName</th>
        <th> FullName</th>
    </tr>
     @foreach (Dictionary<MyProject.Data.Models.User, IEnumerable<MyProject.Data.Models.Role>> item in Model)
     {
        <tr class="detail">
            <td>
                @Html.DisplayFor(modelItem => item.First().Key.UserName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.First().Key.FullName)
            </td>
            <td>
                <ul>
                    @foreach (var role in item.First().Value)
                    {
                        <li>
                            @Html.DisplayFor(modelItem => role.RoleName)
                        </li>
                    }
                </ul>
            </td>
        </tr>
     }
 </table>

    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page}))

您尝试过以下方法吗?

@model PagedList.IPagedList<KeyValuePair<MyProject.Data.Models.User, IEnumerable<MyProject.Data.Models.Role>>>