Blog

MVC 3 and Model Binding

By Carlos Martinez

The System.Web.Mvc namespace contains a class named
DefaultModelBinder, the application object in MVC uses an instance of this class in order to binding all the values inside a post to a given model so it can be passed to an action. For normal scenarios no code is needed for these purposes.

 

When needed, a custom binder can be used in order to implement complex binding logic to a specific action or type. This new custom binder should implement the IModelBinder interface; this binder could be specified in the parameter definition of the post action for example:

 

[HttpPost] public ActionResult Index([ModelBinder(typeof(CustomModelBinder))] CustomModel model)

 

In cases when a binder will be used whenever a certain type is used, the binder could be specified in the application file. Using the following code line (inside the application startup handler):

ModelBinders.Binders.Add(typeof(CustomModel), new CustomModelBinder ());

 

Implementing a custom model binder provider is another way to implement binding logic for our application. The new custom provider should implement the IModelBinderProvider .The only member inside this interface is the GetBinder method; within this method (using only the type as a parameter) all further binder selection logic should be implemented.

 

In order to register a custom model binder provider the following code line should be placed inside the application start handler of the application file:

 

ModelBinderProviders.BinderProviders.Add(new CustomModelBinderProvider());

 

The BinderProviders property inside of the ModelBinderProviders class, is an static member that contains all the binder providers that the application uses.

 

 

Comments

Leave a comment

 
 
 
 
CAPTCHA Image Validation