[ASP.NET][Telerik] RadGrid 分頁、排序和過濾,綁定 ObjectDataSource
開發環境:
Win10 x64 企業版
VS2015 Enterprise
Telerik UI for ASP.NET Ajax 2015.3.1111.45
System.Linq.Dynamic from Nuget
Faker.Net from Nuget
專案位置:
本文開始:
這裡只會針對重點介紹,開始之前,若你不會用 ObjectDataSource,可以參考
http://www.dotblogs.com.tw/yc421206/archive/2014/11/13/147293.aspx
http://www.dotblogs.com.tw/yc421206/archive/2014/11/13/147293.aspx
RadGrid 可以依 欄位 進行過濾,可以透過 radGrid.MasterTableView.FilterExpression 取得過濾條件
看得出來 RadGrid 提供了很多查詢方法,如下圖,
ObjectDataSource 使用 Select 查詢,要注意以下
ObjectDataSource 預設只有三個 Parameter 分別是:StartRowIndexParameterName、MaximumRowsParameterName、SortParameterName
SelectMethod 和 SelectCountMethod 的方法簽章要和 SelectParameters 標籤裡定義的一樣
要讓 ObjectDataSource 能夠吃 RadGrid Filter Bar 所傳過來的資料需要用一點技巧,下圖註冊了 OnSelecting 事件
在 OnSelecting 事件裡面,取得 radGrid.MasterTableView.FilterExpression 後,放到 e.InputParameters["filterExpressions"] ,filterExpressions 就是我們自己定義的 <asp:Parameter Name="filterExpressions"/>
{
var radGrid = this.Master_RadGrid;
this._filterExpression = radGrid.MasterTableView.FilterExpression;
e.InputParameters["filterExpressions"] = this._filterExpression;
}
可以看到 filterExpressions 已經可以拿到 RadGrid 的 Filter 資料
這個專案比較特別的是 Limq.Dynamic 查詢,用來處理 RadGrid 拋過來的 Filter Expression ,這要先 using System.Linq.Dynamic
{
IEnumerable<Employee> query = this._employees.AsQueryable();
if (string.IsNullOrWhiteSpace(filterExpressions) == false)
{
query = query.Where(filterExpressions);
}
this._queryCount = query.Count();
if (string.IsNullOrWhiteSpace(sortExpressions))
{
query = query.OrderBy(p => p.Id);
}
else
{
query = query.OrderBy(sortExpressions);
}
query = query.Skip(startRowIndex).Take(maximumRows);
var result = query.ToList();
return result;
}
再來是利用 Faker.Net 建立看起來像一回事的資料
{
var employees = new List<Employee>();
for (int i = 0; i < 100; i++)
{
var employee = new Employee();
employee.Id = i + 1;
employee.Name = NameFaker.Name();
employee.Birthday = DateTimeFaker.DateTimeBetweenYears(50);
employee.Location = LocationFaker.Country();
employee.Email = InternetFaker.Email();
employees.Add(employee);
}
return employees;
}
Filter Bar 是 AND 條件,這 100 筆的假資料,過濾後的結果如下圖:
本文出自:http://www.dotblogs.com.tw/yc421206/archive/2015/11/18/153971.aspx
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET