我正在创建一个自定义模型绑定器,以在使用传入值更新模型之前从数据库中加载模型。(继承自 DefaultModelBinder)
我需要重写哪种方法才能做到这一点?
我正在创建一个自定义模型绑定器,以在使用传入值更新模型之前从数据库中加载模型。(继承自 DefaultModelBinder)
我需要重写哪种方法才能做到这一点?
您需要重写 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");
}
您需要重写BindModel来执行此操作。