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

ASP.NET 實體類別與表單雙向映射通用輔助類

     編輯:ASP.NET 基礎

核心需求

表單欄位名稱與實體屬性名一致時,自動完成 Form → Entity(新增/編輯存檔)與 Entity → Form(編輯頁面載入)映射,減少重複 txtName.Text = entity.Name 程式碼。

通用靜態類別

using System;
using System.Collections.Specialized;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.HtmlControls;

namespace Com.Fun
{
    public static class FormEntityMapper where T : class, new()
    {
        /// 表單集合 → 實體物件
        public static void BindFromForm(T entity, NameValueCollection form)
        {
            Type type = typeof(T);
            foreach (PropertyInfo prop in type.GetProperties())
            {
                string val = form[prop.Name];
                if (val != null)
                {
                    try
                    {
                        object converted = Convert.ChangeType(val, prop.PropertyType);
                        prop.SetValue(entity, converted, null);
                    }
                    catch { /* 型別不符略過,或記錄日誌 */ }
                }
            }
        }

        /// 實體物件 → 頁面 HtmlInputText 控制項
        public static void BindToForm(T entity, Page page)
        {
            Type type = typeof(T);
            foreach (PropertyInfo prop in type.GetProperties())
            {
                var txt = page.FindControl(prop.Name) as HtmlInputText;
                if (txt != null)
                {
                    object val = prop.GetValue(entity, null);
                    txt.Value = val?.ToString() ?? "";
                }
            }
        }
    }
}

使用範例

// 編輯頁面載入
var model = new HouseRecoDAL().GetModel(id);
FormEntityMapper.BindToForm(model, this.Page);

// 表單提交儲存
var entity = new HouseReco();
FormEntityMapper.BindFromForm(entity, Request.Form);
new HouseRecoDAL().Update(entity);

限制與擴充建議

  • 命名慣例強耦合:表單 name 必須與屬性名完全一致,建議加前綴(txt_Name)並在 Mapper 中對應。
  • 僅支援 HtmlInputText:擴充 DropDownList、CheckBox、TextBox(WebControl)等型別。
  • 型別轉換失敗處理:引入 TryParse 模式或自訂 TypeConverter。
  • 安全性:不可直接對映射開放給前端,需搭配白名單屬性或 ViewModel 隔離,防止過度張貼攻擊。
  • 效能:反射開銷可接受(單次請求毫秒級);高頻場景可用 Expression Tree 編譯快取委派。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved