排序和分页ASP C#

时间:2015-10-02 01:59:11

标签: c# asp.net asp.net-mvc entity-framework pagedlist

我正在尝试在ASP.NET MVC5应用程序中设置搜索,分页和排序。我一直收到以下错误......只有LINQ to Entities中的排序输入才支持'Skip'方法。必须在方法'Skip'之前调用'OrderBy'方法。我正在关注Microsoft指南...(http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

我错过了什么?看起来很简单。

public class npsAAA_dataController : Controller
{
    private npsAAAEntities db = new npsAAAEntities();

    // GET: npsAAA_data
    public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page)
    {
        ViewBag.CurrentSort = sortOrder;
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        if (searchString != null)
            page = 1;
        else
            searchString = currentFilter;

        ViewBag.CurrentFilter = searchString;
        var user = from s in db.accounting_data select s;

        if(!String.IsNullOrEmpty(searchString))
        {
            user = user.Where(s => s.User_Name.Contains(searchString));
        }
        switch(sortOrder)
        {
            case "name_desc":
                user = user.OrderByDescending(s => s.User_Name);
                break;
            case "Date":
                user = user.OrderBy(s => s.timestamp);
                break;
            case "date_desc":
                user = user.OrderByDescending(s => s.timestamp);
                break;
            default:
                user = user.OrderBy(s => s.User_Name);
                break;

        }
        int pageSize = 10;
        int pageNumber = (page ?? 1);
        return View(db.accounting_data.ToPagedList(pageNumber,pageSize));
    }

1 个答案:

答案 0 :(得分:1)

您没有在return View()行返回已排序的数据。您当前的代码将已排序的数据分配给user,但随后您将其忽略,而是再次调用数据库以返回未排序的数据。请将您的代码更改为:

return View(user.ToPagedList(pageNumber, pageSize));