Custom model binder for a property

rrejc picture rrejc · Feb 2, 2010 · Viewed 24.7k times · Source

I have the following controller action:

[HttpPost]
public ViewResult DoSomething(MyModel model)
{
    // do something
    return View();
}

Where MyModel looks like this:

public class MyModel
{
    public string PropertyA {get; set;}
    public IList<int> PropertyB {get; set;}
}

So DefaultModelBinder should bind this without a problem. The only thing is that I want to use special/custom binder for binding PropertyB and I also want to reuse this binder. So I thought that solution would be to put a ModelBinder attribute before the PropertyB which of course doesn't work (ModelBinder attribute is not allowed on a properties). I see two solutions:

  1. To use action parameters on every single property instead of the whole model (which I wouldn't prefer as the model has a lot of properties) like this:

    public ViewResult DoSomething(string propertyA, [ModelBinder(typeof(MyModelBinder))] propertyB)
    
  2. To create a new type lets say MyCustomType: List<int> and register model binder for this type (this is an option)

  3. Maybe to create a binder for MyModel, override BindProperty and if the property is "PropertyB" bind the property with my custom binder. Is this possible?

Is there any other solution?

Answer

queen3 picture queen3 · Feb 3, 2010

override BindProperty and if the property is "PropertyB" bind the property with my custom binder

That's a good solution, though instead of checking "is PropertyB" you better check for your own custom attributes that define property-level binders, like

[PropertyBinder(typeof(PropertyBBinder))]
public IList<int> PropertyB {get; set;}

You can see an example of BindProperty override here.