What should a BindModel() implementation do?

3.1k views Asked by At

I've been reading the MVC 3 source code trying to understand what semantics I should adhere to if I override DefaultModelBinder.BindModel() or even implement IModelBinder.BindModel().

It's unclear to me what "state" BindModel() should leave other objects in once it's done with its work. Sure it's suppose to return a value representing some interpretation of ValueProvider data, but what side effects is it supposed to have? For example:

  • Does MVC have expectations about state of the bindingContext passed to BindModel() *after* the method has finished?
  • What, if anything, should IModelBinder.BindModel() set in ModelMetadata? (DefaultModelBinder sets property metadata in its BindProperty() method, called by BindModel().)
  • Should an override of DefaultModelBinder.BindModel() call ModelState.AddModelError(), or is a BindProperty() override a more appropriate place (especially if I want to take advantage of DefaultModelBinder's default behaviors as much as possible)?

DefaultModelBinder has so many semantics built into its plumbing that it makes overriding anything it feel very dangerous (i.e. I feel like I can't override anything without violating the Liskov principle). Lack of documentation doesn't help.

1

There are 1 answers

0
Pierrick On

If you need custom binding I would implement the IModelBinder interface and do what's necessary to build your object.