2

I am creating a custom model binder to initially load a model from the database before updating the model with incoming values. (Inheriting from DefaultModelBinder)

Which method do I need to override to do this?

kroehre
  • 1,104
  • 5
  • 15

2 Answers2

3

You need to override the BindModel method of the DefaultModelBinder base class:

    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");
    } 
m0sa
  • 10,712
  • 4
  • 44
  • 91
  • Do I need to bind each property manually after loading from the database or will that still happen automatically? – kroehre Jun 01 '11 at 20:59
  • You need to bind each property manually, or delegate it to the base class. – m0sa Jun 01 '11 at 21:29
0

You'll want to override BindModel to do this.

Tejs
  • 40,736
  • 10
  • 68
  • 86