使用PagedList.Mvc时出错

时间:2014-12-19 10:39:23

标签: c# asp.net-mvc

我试图使用pagedList.mvc包来查询我从查询中得到的结果,我在我的控制器中这样做了。

 public ActionResult AllPosts()
    {
       int pageSize = 4;
       int pageNum = (page ?? 1);
       var query = from p in db.Posts
select new ListPostsVM()
                    {
                        PostTitle = p.PostTitle,
                        Author = p.UserProfile.UserName,
                        DateCreated = p.DateCreated,
                        CategoryName = p.Category.CategoryName
                    };
return View(query.ToPagedList(pageNum, pageSize));
    }

在我看来我做了这个

@model IPagedList<Blogger.ViewModels.ListPostsVM>
@using PagedList;
@using PagedList.Mvc;
@{
    ViewBag.Title = "AllPosts";
    Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<link href="~/Content/PagedList.css" rel="stylesheet" />
<h2>AllPosts</h2>
<div class="allposts">
    <table class="table">
        <tr>
            <th>Title</th>
            <th>Author</th>
            <th>Category</th>
            <th>Date</th>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.PostTitle
                 <p class="actions">
                    Edit | Delete | View
                 </p>
                </td>
                <td>@item.Author</td>
                <td>@item.CategoryName</td>
                <td>@item.DateCreated</td>
            </tr>
        }
    </table>
</div>

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

然而,当我运行构建此代码并导航到该页面时,我收到错误说

An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

Additional information: The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

你回来了错误的类型。

即。 return View(query.ToPagedList(pageNum, pageSize));

您应该将代码更改为:

return View(query.OrderBy(x => x.Author).ToPagedList(pageNumber, pageSize));

答案 1 :(得分:0)

根据this link,您必须将return声明更新为以下内容:

return View(query.OrderBy(x => x.PostTitle).ToPagedList(pageNum, pageSize));