在 WebForms 中像 MVC 一樣:UserModel model = AssembleModel<UserModel>(); 自動將 Request.Params 按屬性名映射到實體。
public class BasePage : Page
{
protected NameValueCollection ValueCollection = HttpContext.Current.Request.Params;
protected PropertyInfo[] GetPropertyInfoArray(Type type)
{
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
protected T AssembleModel<T>(NameValueCollection collection) where T : new()
{
var props = GetPropertyInfoArray(typeof(T));
var obj = Activator.CreateInstance<T>();
foreach (string key in collection.Keys)
{
foreach (var prop in props)
{
if (key.Equals(prop.Name, StringComparison.OrdinalIgnoreCase))
{
prop.SetValue(obj, collection[key], null);
break; // 匹配到即跳出內層循環
}
}
}
return obj;
}
}
public partial class Register : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) InitPage();
else
{
var model = AssembleModel<UserModel>(base.ValueCollection);
// 直接使用 model 進行業務處理
}
}
}
Convert.ChangeType 或 TypeDescriptor.GetConverter 處理 int、DateTime、enum 等。prefix 參數,適配 form1.txtName 命名容器場景。DataAnnotations + 自定義 ValidateModel 方法,實現 MVC 風格 ModelState.IsValid。PropertyInfo[] 避免反射開銷。| 特性 | 本實現 | MVC DefaultModelBinder |
|---|---|---|
| 嵌套對象 | 不支援 | 支援 |
| 集合綁定 | 不支援 | 支援 |
| 類型轉換 | 基礎 | 完整(含自定義) |
| 驗證 | 無 | DataAnnotations + IValidatableObject |
作為輕量級補丁足夠應付多數 WebForms 遷移/維護場景。