首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

Hxj.Data 實現 ASP.NET 頁面自動雙向繫結:EntityUtils.SetDocumentValue / UpdateModel

     編輯:關於ASP.NET

痛點:大量欄位的手工賦值/取值體力活

編輯頁面常有 20+ 欄位,手寫 txtName.Text = entity.Name、entity.Name = txtName.Text 既繁瑣又易漏。Hxj.Data 內建 EntityUtils 輔助類,依慣例命名自動完成雙向繫結。

命名慣例

頁面控制項 ID = 前綴 + 實體屬性名,例如前綴 txt_:

  • txt_ProductName → entity.ProductName
  • txt_UnitPrice → entity.UnitPrice
  • txt_Discontinued (CheckBox) → entity.Discontinued (bool)

實體類別(Products)

public class Products : Entity {
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int? SupplierID { get; set; }
    public int? CategoryID { get; set; }
    public string QuantityPerUnit { get; set; }
    public decimal? UnitPrice { get; set; }
    public int? UnitsInStock { get; set; }
    public int? UnitsOnOrder { get; set; }
    public int? ReorderLevel { get; set; }
    public bool Discontinued { get; set; }
}

ASPX 頁面片段

<form id="form1" runat="server">
    ProductName:<asp:TextBox ID="txt_ProductName" runat="server" /><br />
    SupplierID:<asp:TextBox ID="txt_SupplierID" runat="server" /><br />
    CategoryID:<asp:TextBox ID="txt_CategoryID" runat="server" /><br />
    QuantityPerUnit:<asp:TextBox ID="txt_QuantityPerUnit" runat="server" /><br />
    UnitPrice:<asp:TextBox ID="txt_UnitPrice" runat="server" /><br />
    UnitsInStock:<asp:TextBox ID="txt_UnitsInStock" runat="server" /><br />
    UnitsOnOrder:<asp:TextBox ID="txt_UnitsOnOrder" runat="server" /><br />
    ReorderLevel:<asp:TextBox ID="txt_ReorderLevel" runat="server" /><br />
    Discontinued:<asp:CheckBox ID="txt_Discontinued" runat="server" /><br />
    <asp:Button ID="Button1" Text="提交Insert" OnClick="Button1_Click" />
    <asp:GridView ID="gridView" runat="server" />
</form>

Code-behind:一鍵賦值與取值

// 1. 查詢實體 → 自動填入頁面(編輯/詳情頁)
Products product = DbSession.Default.From().ToFirst();
EntityUtils.SetDocumentValue(product, "txt_"); // 關鍵:前綴 "txt_"

// 2. 頁面輸入 → 自動填入實體(新增/修改頁)
protected void Button1_Click(object sender, EventArgs e) {
    Products p = new Products();
    EntityUtils.UpdateModel(p, "txt_"); // 讀取所有 txt_* 控制項值
    
    int newId = DbSession.Default.Insert(p);
    gridView.DataSource = DbSession.Default.From()
                                .Where(Products._.ProductID == newId).ToList();
    gridView.DataBind();
}

支援型別與控制項

CLR 型別對應控制項取值/賦值方式
stringTextBox, HiddenField, Label.Text
int, decimal, DateTime, bool 等TextBox.Text → TypeConverter 轉換
boolCheckBox.Checked
enumDropDownList, RadioButtonList.SelectedValue

自動處理 null、DBNull、空字串轉換,型別不符時不拋出例外、只略過並記錄 Debug 訊息。

效果展示

自動賦值成功截圖

所有欄位瞬間填入資料,零手工程式碼。修改後按下「提交」同樣一行 UpdateModel 完成回寫,極大提升開發效率。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved