Search code examples
c#asp.netasp.net-mvcentity-frameworkpagedlist

Sorted and Paged ASP C#


I am trying to setup search,paging, and sorting in my ASP.NET MVC5 application. I keep getting the following error...The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'. I am following the Microsoft Guide... (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)

What am I missing? It seems pretty straight forward.

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

Solution

  • You are not returning your sorted data in the return View() line. Your current code is assigning the sorted data to user, but then you ignore it and instead call the database again to return unsorted data. Change your code into this instead:

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