2011-06-01 153 views

回答

3

你需要重寫DefaultModelBinder基類的BindModel方法:

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType == typeof(YourType)) 
     { 
      var instanceOfYourType = ...; 
      // load YourType from DB etc.. 

      var newBindingContext = new ModelBindingContext 
      { 
       ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => instanceOfYourType, typeof(YourType)), 
       ModelState = bindingContext.ModelState, 
       FallbackToEmptyPrefix = bindingContext.FallbackToEmptyPrefix, 
       ModelName = bindingContext.FallbackToEmptyPrefix ? string.Empty : bindingContext.ModelName, 
       ValueProvider = bindingContext.ValueProvider, 
      }; 
      if (base.OnModelUpdating(controllerContext, newBindingContext)) // start loading.. 
      { 
       // bind all properties: 
       base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property1", false)); 
       base.BindProperty(controllerContext, bindingContext, TypeDescriptor.GetProperties(typeof(YourType)).Find("Property2", false)); 

       // trigger the validators: 
       base.OnModelUpdated(controllerContext, newBindingContext); 
      } 

      return instanceOfYourType; 
     }    
     throw new InvalidOperationException("Supports only YourType objects"); 
    } 
+0

我需要從數據庫或意願仍自動加載發生後手動每個屬性綁定? – kroehre 2011-06-01 20:59:19

+0

您需要手動綁定每個屬性,或者將其委派給基類。 – m0sa 2011-06-01 21:29:50