C# .Net MVC3自定义模型绑定器-初始加载模型
我正在创建一个自定义模型绑定器,以便在使用传入值更新模型之前,首先从数据库加载模型。(从DefaultModelBinder继承)C# .Net MVC3自定义模型绑定器-初始加载模型,c#,.net,asp.net-mvc-3,modelbinders,defaultmodelbinder,C#,.net,Asp.net Mvc 3,Modelbinders,Defaultmodelbinder,我正在创建一个自定义模型绑定器,以便在使用传入值更新模型之前,首先从数据库加载模型。(从DefaultModelBinder继承) 要执行此操作,我需要覆盖哪个方法?您需要覆盖 您需要覆盖DefaultModelBinder基类的BindModel方法: public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
要执行此操作,我需要覆盖哪个方法?您需要覆盖 您需要覆盖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");
}
从数据库加载后是否需要手动绑定每个属性,还是仍然自动绑定?您需要手动绑定每个属性,或者将其委托给基类。