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

ASP.NET MVC Beta 自動模型繫結深度探索:DefaultModelBinder 內部機制

     編輯:關於ASP.NET

ASP.NET MVC Beta 引入自動模型繫結,DefaultModelBinder 取代 Preview 5 手寫 IModelBinder 的繁瑣。本文深入原始碼分析 ControllerActionInvoker 如何調用繫結管線、BindAttribute 如何控制繫結行為、ModelBinderContext 如何封裝繫結上下文。

繫結管線入口:ControllerActionInvoker

protected virtual object GetParameterValue(ControllerContext context, ParameterDescriptor parameter)
{
    IModelBinder binder = GetModelBinder(parameter);  // 取得繫結器
    ModelBinderContext bindingContext = new ModelBinderContext
    {
        ModelName = parameter.ParameterName,
        ModelType = parameter.ParameterType,
        ValueProvider = context.Controller.ValueProvider,
        PropertyFilter = GetPropertyFilter(parameter)  // 來自 BindAttribute
    };
    BinderResult result = binder.BindModel(context, bindingContext);
    return result.Model;
}

核心類別職責

類別/介面職責
BindAttribute修飾 Action 參數,控制 Include/Exclude/Prefix、IsPropertyAllowed 謂詞
DefaultModelBinder預設繫結實作,遞迴處理複雜類型屬性
ModelBinderContext封裝繫結所需:ModelName、ModelType、ValueProvider、PropertyFilter
BinderResult封裝繫結結果:Model、IsModelSet
IValueProvider抽象值來源(Form、QueryString、RouteData),統一繫結介面

BindAttribute 控制繫結細節

public class BindAttribute : Attribute
{
    public string Include { get; set; }      // 允許繫結屬性(逗號分隔)
    public string Exclude { get; set; }      // 排除屬性
    public string Prefix { get; set; }       // 表單欄位前綴
    public bool IsPropertyAllowed(string propertyName)  // 判斷屬性是否可繫結
}

用法:

public ActionResult Create([Bind(Include="Name,Price")] Product product) { ... }

DefaultModelBinder 遞迴繫結邏輯

  1. 簡單型別(string、int、DateTime 等):直接從 ValueProvider 取值轉型
  2. 複雜型別:建立實例,對每個公開可寫屬性遞迴呼叫 BindProperty
  3. 集合型別:依索引 Prefix[0].Property 繫結每個元素
  4. 每層檢查 PropertyFilter(來自 BindAttribute.IsPropertyAllowed)決定是否繫結

擴充點:自訂 ModelBinder

public class CustomBinder : IModelBinder
{
    public object BindModel(ControllerContext context, ModelBindingContext bindingContext)
    {
        // 自訂繫結邏輯
    }
}

// 註冊
ModelBinders.Binders.Add(typeof(MyType), new CustomBinder());
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved