MVC3 でページング


1. まずは、サンプルデータベース AdventureWorks をインストール。

http://msftdbprodsamples.codeplex.com/releases/view/55926

2. Model に、Contact の Entity Framework の追加

Model を右クリック、新しい項目の追加より、データのADO.NET Enitity Data Model を選択。

モデルに含めるコンテンツで、データベースから生成を選択。テーブルで Contactを選択。

3. Controller

Action として、Contact を追加。

using MvcApplication8.Models;

AdventureWorksEntities ae = new AdventureWorksEntities();

public ActionResult Contact()
{
    ViewBag.Message = “ASP.NET MVC へようこそ”;

    return View(ae.Contact.ToList());
}

4. Viewとして、Contact を追加。

Razorビューエンジンで、スキャフォールディングのListを選択。

このままだと、すべてのページを表示してしまうので、10レコードづつ表示するページングが必要。

そこで、次のようにルーティングを定義して、
routes.MapRoute(
    “Contact”, // ルート名
    “{controller}/{action}/{page}”, // パラメーター付きの URL
    new { controller = “Home”, action = “Contact”, page = 1 } // パラメーターの既定値
);

Contact Action でページを指定してあげる。

public ActionResult Contact(int page)
{
    ViewBag.Message = “ASP.NET MVC へようこそ”;

    var res = (from x in ae.Contact select x).OrderBy(x=>x.FirstName).Skip(page * 10).Take(10);

    return View(res);
}

これで、http://…/Home/Contact/789 で、789ページ目から10人分だけ表示するページング。

image

なお、OrderByしないと、次のエラーになるので、OrderByは必要。

メソッド ‘Skip’ は、LINQ to Entities では並べ替え済みの入力に対してのみサポートされます。メソッド ‘Skip’ の前にメソッド ‘OrderBy’ を呼び出す必要があります。

なお、Paging performance with Skip/Take

http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/45a9172b-c2fe-4be5-b36b-9ec708f0998e

によると、Linq の Skip / Take はかなり早いようだ。

コメントを残す