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

ASP.NET WebForms 實現 MVC 風格模型綁定:基類一鍵裝配 Request 到實體

     編輯:ASP.NET 基礎

目標

在 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

特性本實現MVC DefaultModelBinder
嵌套對象不支援支援
集合綁定不支援支援
類型轉換基礎完整(含自定義)
驗證無DataAnnotations + IValidatableObject

作為輕量級補丁足夠應付多數 WebForms 遷移/維護場景。

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