.Net MVC3自定义模型粘合剂 - 最初加载模型

时间:2011-06-01 20:48:53

标签: c# .net asp.net-mvc-3 modelbinders defaultmodelbinder

我正在创建一个自定义模型绑定器,以便在使用传入值更新模型之前从数据库初始加载模型。 (继承自DefaultModelBinder)

我需要覆盖哪种方法来执行此操作?

2 个答案:

答案 0 :(得分: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");
    } 

答案 1 :(得分:0)

您需要覆盖BindModel才能执行此操作。