表單欄位名稱與實體屬性名一致時,自動完成 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 中對應。DropDownList、CheckBox、TextBox(WebControl)等型別。TryParse 模式或自訂 TypeConverter。Expression Tree 編譯快取委派。