How do I implement paging to "Controller/ with read/write actions and views, using Entity Framework" wizard-generated code?
This is ASP.MVC 3 controller code generated by the "Controller/ with read/write actions and views, using Entity Framework" Wizard packaged with the EF 4.1 tooling. It works great in demos when you have 10-20 records, but when you pull data from a DbContext with 10,000+ records, it obviously slows way down and produces an unusably long page.
So, how would you modify Index() to implement paging in the db.Courses.ToList()?
// wizard generated MVC Controller code
namespace Scheduler.Controllers
{
public class CourseController : Controller
{
private CourseEntities 开发者_运维百科db = new CourseEntities();
//
// GET: /Course/
public ViewResult Index()
{
// returns over 10,000 courses in the list
return View(db.Courses.ToList());
}
}
}
Seems a little Linq to Entities is in order.
Here's my modified Index() controller:
public ViewResult Index(int page = 0)
{
int pageSize = 10;
var courses = db.Courses.OrderBy(c => c.Id).Skip(page * pageSize).Take(pageSize);
return View(courses);
}
Then construct links in the View that append the page parameter to the url like this:
/Course?page=2
You can use the PagedList NuGet package. See this tutorial: http://www.asp.net/entity-framework/tutorials/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
精彩评论