igGrid では、バインドデータの並び替えをサーバー側で行う機能に対応しています。igGrid に対してソート処理を実行すると、igGrid のデータソースとして参照しているアクションを呼び出します。
呼び出されたアクション側では、クエリパラメータに含まれている並び替え情報(列、並べ替え順序)を元に、データを並び替えた上でデータを返却します。
Index.cshtml
$("#grid").igGrid({
primaryKey: "Id",
height: "500px",
dataSource: "/Home/BindSorting",
features: [
{
name: "Sorting",
type: "remote"
}
]
});
HomeController.cs
public JsonResult BindSorting()
{
// ダミーデータの取得
var products = GetProducts();
/*クエリパラメータに含まれるソート情報を元に、データソースを並び替える*/
var orderByInfo = Request.Query["$orderby"];
// ソートしていない場合
if(orderByInfo.Count == 0)
{
return new JsonResult(products);
}
// ソートしている場合
var sortingInfo = orderByInfo[0].Split(' ');
var fieldName = sortingInfo[0];
var sortDirection = sortingInfo[1];
List<Product> orderedProducts = null;
// 昇順
if (sortDirection == "asc")
{
orderedProducts =
products.OrderBy(s => s.GetType().GetProperty(fieldName).GetValue(s)).ToList();
}
// 降順
else
{
orderedProducts =
products.OrderByDescending(s => s.GetType().GetProperty(fieldName).GetValue(s)).ToList();
}
return new JsonResult(orderedProducts);
}