傳統 WebForms 在後台撰寫大量資料繫結、分頁、參數處理程式碼。本文提出以自訂 DataSourceControl 封裝資料邏輯,讓頁面回歸宣告式開發,減少 Code-Behind。
DataSourceControl (或 ObjectDataSource) 的元件。DataSourceID="ds",自動完成查詢、分頁、排序、更新。public class ProductDataSource : NBearDataSource
{
protected override void OnSelecting(DataSourceSelectArguments e)
{
// 依據參數建構 WhereClip
var where = new WhereClip();
if (!string.IsNullOrEmpty(this.CategoryId))
where &= Product.__CategoryId == this.CategoryId;
this.Filter = where;
base.OnSelecting(e);
}
}
<asp:MyProductDataSource ID="ProductDS" runat="server"
CategoryId='<%# Request.QueryString["cat"] %>' />
<asp:GridView ID="gv" runat="server" DataSourceID="ProductDS" AllowPaging="True" AllowSorting="True" />
| 面向 | 傳統 Code-Behind | DataSourceControl 封裝 |
|---|---|---|
| 分頁/排序程式碼 | 每頁重寫 | 控制項內建自動處理 |
| 參數取得 | 手寫 Request/Control 值 | 宣告式 Parameter 綁定 |
| 更新/新增欄位對應 | 手動 FindControl 賦值 | 雙向綁定自動映射實體 |
| 邏輯重用 | 複製貼上 | 元件化、跨專案共用 |
| 維護性 | 分散在各頁 | 集中在 DataSource 類別 |